abccbf6d395886fb2584c2fd887b0da54723977e
[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 case HTTPoison.get(endpoint <> "/new") do
11 {:error, _} ->
12 %{error: "Kocaptcha service unavailable"}
13 {:ok, res} ->
14 json_resp = Poison.decode!(res.body)
15
16 token = json_resp["token"]
17
18 true = :ets.insert(@ets, {token, json_resp["md5"]})
19
20 %{type: :kocaptcha, token: token, url: endpoint <> json_resp["url"]}
21 end
22 end
23
24 @impl Service
25 def validate(token, captcha) do
26 with false <- is_nil(captcha),
27 [{^token, saved_md5}] <- :ets.lookup(@ets, token),
28 true <- (:crypto.hash(:md5, captcha) |> Base.encode16) == String.upcase(saved_md5) do
29 # Clear the saved value
30 :ets.delete(@ets, token)
31
32 true
33 else
34 _ -> false
35 end
36 end
37 end