df33406ee7777f0235ee34db0ffd60293d6b8848
[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 {:reply, method().new(), state}
42 end
43 end
44
45 @doc false
46 def handle_call({:validate, token, captcha}, _from, state) do
47 {:reply, method().validate(token, captcha), state}
48 end
49
50 defp method, do: Pleroma.Config.get!([__MODULE__, :method])
51 end