Change minutes_retained config to seconds_retained
[akkoma] / lib / pleroma / captcha / captcha.ex
1 defmodule Pleroma.Captcha do
2 use GenServer
3
4 @ets_options [:ordered_set, :private, :named_table, {:read_concurrency, true}]
5
6 @doc false
7 def start_link() do
8 GenServer.start_link(__MODULE__, [], name: __MODULE__)
9 end
10
11 @doc false
12 def init(_) do
13 # Create a ETS table to store captchas
14 ets_name = Module.concat(method(), Ets)
15 ^ets_name = :ets.new(Module.concat(method(), Ets), @ets_options)
16
17 {:ok, nil}
18 end
19
20 @doc """
21 Ask the configured captcha service for a new captcha
22 """
23 def new() do
24 GenServer.call(__MODULE__, :new)
25 end
26
27 @doc """
28 Ask the configured captcha service to validate the captcha
29 """
30 def validate(token, captcha) do
31 GenServer.call(__MODULE__, {:validate, token, captcha})
32 end
33
34 @doc false
35 def handle_call(:new, _from, state) do
36 enabled = Pleroma.Config.get([__MODULE__, :enabled])
37
38 if !enabled do
39 {:reply, %{type: :none}, state}
40 else
41 new_captcha = method().new()
42
43 seconds_retained = Pleroma.Config.get!([__MODULE__, :seconds_retained])
44 # Wait several minutes and if the captcha is still there, delete it
45 Process.send_after(self(), {:cleanup, new_captcha.token}, 1000 * seconds_retained)
46
47 {:reply, new_captcha, state}
48 end
49 end
50
51 @doc false
52 def handle_call({:validate, token, captcha}, _from, state) do
53 {:reply, method().validate(token, captcha), state}
54 end
55
56 @doc false
57 def handle_info({:cleanup, token}, state) do
58 method().cleanup(token)
59
60 {:noreply, state}
61 end
62
63 defp method, do: Pleroma.Config.get!([__MODULE__, :method])
64 end