9891d403179422b650a02765330446c704eed998
[akkoma] / lib / pleroma / captcha / kocaptcha.ex
1 defmodule Pleroma.Captcha.Kocaptcha do
2 alias Pleroma.Captcha.Service
3 @behaviour Service
4
5 @ets __MODULE__.Ets
6
7 @impl Service
8 def new() do
9 endpoint = Pleroma.Config.get!([__MODULE__, :endpoint])
10
11 case Tesla.get(endpoint <> "/new") do
12 {:error, _} ->
13 %{error: "Kocaptcha service unavailable"}
14
15 {:ok, res} ->
16 json_resp = Poison.decode!(res.body)
17
18 token = json_resp["token"]
19
20 true = :ets.insert(@ets, {token, json_resp["md5"]})
21
22 %{type: :kocaptcha, token: token, url: endpoint <> json_resp["url"]}
23 end
24 end
25
26 @impl Service
27 def validate(token, captcha) do
28 with false <- is_nil(captcha),
29 [{^token, saved_md5}] <- :ets.lookup(@ets, token),
30 true <- :crypto.hash(:md5, captcha) |> Base.encode16() == String.upcase(saved_md5) do
31 # Clear the saved value
32 cleanup(token)
33
34 true
35 else
36 _ -> false
37 end
38 end
39
40 @impl Service
41 def cleanup(token) do
42 # Only delete the entry if it exists in the table, because ets:delete raises an exception if it does not
43 case :ets.lookup(@ets, token) do
44 [{^token, _}] -> :ets.delete(@ets, token)
45 _ -> true
46 end
47 end
48 end