Clean captchas up periodically, not schedule it after theyre created
[akkoma] / lib / pleroma / captcha / kocaptcha.ex
1 defmodule Pleroma.Captcha.Kocaptcha do
2 alias Calendar.DateTime
3
4 alias Pleroma.Captcha.Service
5 @behaviour Service
6
7 @ets __MODULE__.Ets
8
9 @impl Service
10 def new() do
11 endpoint = Pleroma.Config.get!([__MODULE__, :endpoint])
12
13 case Tesla.get(endpoint <> "/new") do
14 {:error, _} ->
15 %{error: "Kocaptcha service unavailable"}
16
17 {:ok, res} ->
18 json_resp = Poison.decode!(res.body)
19
20 token = json_resp["token"]
21
22 true = :ets.insert(@ets, {token, json_resp["md5"], DateTime.now_utc()})
23
24 %{type: :kocaptcha, token: token, url: endpoint <> json_resp["url"]}
25 end
26 end
27
28 @impl Service
29 def validate(token, captcha) do
30 with false <- is_nil(captcha),
31 [{^token, saved_md5, _}] <- :ets.lookup(@ets, token),
32 true <- :crypto.hash(:md5, captcha) |> Base.encode16() == String.upcase(saved_md5) do
33 # Clear the saved value
34 :ets.delete(@ets, token)
35
36 true
37 else
38 _ -> false
39 end
40 end
41
42 @impl Service
43 def cleanup() do
44 seconds_retained = Pleroma.Config.get!([Pleroma.Captcha, :seconds_retained])
45
46 # Go through captchas and remove expired ones
47 :ets.tab2list(@ets)
48 |> Enum.each(fn {token, _, time_inserted} ->
49 # time created + expiration time = time when the captcha should be removed
50 remove_time = DateTime.add!(time_inserted, seconds_retained)
51 if DateTime.after?(DateTime.now_utc(), remove_time), do: :ets.delete(@ets, token)
52 end)
53
54 :ok
55 end
56 end