Merge branch 'develop' into oembed_provider
[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 =
23 :ets.insert(
24 @ets,
25 {token, json_resp["md5"], DateTime.now_utc() |> DateTime.Format.unix()}
26 )
27
28 %{type: :kocaptcha, token: token, url: endpoint <> json_resp["url"]}
29 end
30 end
31
32 @impl Service
33 def validate(token, captcha) do
34 with false <- is_nil(captcha),
35 [{^token, saved_md5, _}] <- :ets.lookup(@ets, token),
36 true <- :crypto.hash(:md5, captcha) |> Base.encode16() == String.upcase(saved_md5) do
37 # Clear the saved value
38 :ets.delete(@ets, token)
39
40 true
41 else
42 _ -> false
43 end
44 end
45
46 @impl Service
47 def cleanup() do
48 seconds_retained = Pleroma.Config.get!([Pleroma.Captcha, :seconds_retained])
49 # If the time in ETS is less than current_time - seconds_retained, then the time has
50 # already passed
51 delete_after =
52 DateTime.subtract!(DateTime.now_utc(), seconds_retained) |> DateTime.Format.unix()
53
54 :ets.select_delete(
55 @ets,
56 [
57 {
58 {:_, :_, :"$1"},
59 [{:<, :"$1", {:const, delete_after}}],
60 [true]
61 }
62 ]
63 )
64
65 :ok
66 end
67 end