Add docs/Admin-API.md
[akkoma] / lib / pleroma / captcha / captcha.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Captcha do
6 use GenServer
7
8 @ets_options [:ordered_set, :private, :named_table, {:read_concurrency, true}]
9
10 @doc false
11 def start_link() do
12 GenServer.start_link(__MODULE__, [], name: __MODULE__)
13 end
14
15 @doc false
16 def init(_) do
17 # Create a ETS table to store captchas
18 ets_name = Module.concat(method(), Ets)
19 ^ets_name = :ets.new(Module.concat(method(), Ets), @ets_options)
20
21 # Clean up old captchas every few minutes
22 seconds_retained = Pleroma.Config.get!([__MODULE__, :seconds_retained])
23 Process.send_after(self(), :cleanup, 1000 * seconds_retained)
24
25 {:ok, nil}
26 end
27
28 @doc """
29 Ask the configured captcha service for a new captcha
30 """
31 def new() do
32 GenServer.call(__MODULE__, :new)
33 end
34
35 @doc """
36 Ask the configured captcha service to validate the captcha
37 """
38 def validate(token, captcha) do
39 GenServer.call(__MODULE__, {:validate, token, captcha})
40 end
41
42 @doc false
43 def handle_call(:new, _from, state) do
44 enabled = Pleroma.Config.get([__MODULE__, :enabled])
45
46 if !enabled do
47 {:reply, %{type: :none}, state}
48 else
49 {:reply, method().new(), state}
50 end
51 end
52
53 @doc false
54 def handle_call({:validate, token, captcha}, _from, state) do
55 {:reply, method().validate(token, captcha), state}
56 end
57
58 @doc false
59 def handle_info(:cleanup, state) do
60 :ok = method().cleanup()
61
62 seconds_retained = Pleroma.Config.get!([__MODULE__, :seconds_retained])
63 # Schedule the next clenup
64 Process.send_after(self(), :cleanup, 1000 * seconds_retained)
65
66 {:noreply, state}
67 end
68
69 defp method, do: Pleroma.Config.get!([__MODULE__, :method])
70 end