Merge branch 'features/add-credo-to-ci' into 'develop'
[akkoma] / lib / pleroma / captcha / captcha.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Captcha do
6 alias Calendar.DateTime
7 alias Plug.Crypto.KeyGenerator
8 alias Plug.Crypto.MessageEncryptor
9
10 use GenServer
11
12 @doc false
13 def start_link do
14 GenServer.start_link(__MODULE__, [], name: __MODULE__)
15 end
16
17 @doc false
18 def init(_) do
19 {:ok, nil}
20 end
21
22 @doc """
23 Ask the configured captcha service for a new captcha
24 """
25 def new do
26 GenServer.call(__MODULE__, :new)
27 end
28
29 @doc """
30 Ask the configured captcha service to validate the captcha
31 """
32 def validate(token, captcha, answer_data) do
33 GenServer.call(__MODULE__, {:validate, token, captcha, answer_data})
34 end
35
36 @doc false
37 def handle_call(:new, _from, state) do
38 enabled = Pleroma.Config.get([__MODULE__, :enabled])
39
40 if !enabled do
41 {:reply, %{type: :none}, state}
42 else
43 new_captcha = method().new()
44
45 secret_key_base = Pleroma.Config.get!([Pleroma.Web.Endpoint, :secret_key_base])
46
47 # This make salt a little different for two keys
48 token = new_captcha[:token]
49 secret = KeyGenerator.generate(secret_key_base, token <> "_encrypt")
50 sign_secret = KeyGenerator.generate(secret_key_base, token <> "_sign")
51 # Basicallty copy what Phoenix.Token does here, add the time to
52 # the actual data and make it a binary to then encrypt it
53 encrypted_captcha_answer =
54 %{
55 at: DateTime.now_utc(),
56 answer_data: new_captcha[:answer_data]
57 }
58 |> :erlang.term_to_binary()
59 |> MessageEncryptor.encrypt(secret, sign_secret)
60
61 {
62 :reply,
63 # Repalce the answer with the encrypted answer
64 %{new_captcha | answer_data: encrypted_captcha_answer},
65 state
66 }
67 end
68 end
69
70 @doc false
71 def handle_call({:validate, token, captcha, answer_data}, _from, state) do
72 secret_key_base = Pleroma.Config.get!([Pleroma.Web.Endpoint, :secret_key_base])
73 secret = KeyGenerator.generate(secret_key_base, token <> "_encrypt")
74 sign_secret = KeyGenerator.generate(secret_key_base, token <> "_sign")
75
76 # If the time found is less than (current_time-seconds_valid) then the time has already passed
77 # Later we check that the time found is more than the presumed invalidatation time, that means
78 # that the data is still valid and the captcha can be checked
79 seconds_valid = Pleroma.Config.get!([Pleroma.Captcha, :seconds_valid])
80 valid_if_after = DateTime.subtract!(DateTime.now_utc(), seconds_valid)
81
82 result =
83 with {:ok, data} <- MessageEncryptor.decrypt(answer_data, secret, sign_secret),
84 %{at: at, answer_data: answer_md5} <- :erlang.binary_to_term(data) do
85 try do
86 if DateTime.before?(at, valid_if_after), do: throw({:error, "CAPTCHA expired"})
87
88 if not is_nil(Cachex.get!(:used_captcha_cache, token)),
89 do: throw({:error, "CAPTCHA already used"})
90
91 res = method().validate(token, captcha, answer_md5)
92 # Throw if an error occurs
93 if res != :ok, do: throw(res)
94
95 # Mark this captcha as used
96 {:ok, _} =
97 Cachex.put(:used_captcha_cache, token, true, ttl: :timer.seconds(seconds_valid))
98
99 :ok
100 catch
101 :throw, e -> e
102 end
103 else
104 _ -> {:error, "Invalid answer data"}
105 end
106
107 {:reply, result, state}
108 end
109
110 defp method, do: Pleroma.Config.get!([__MODULE__, :method])
111 end