Refactor a little bit
[akkoma] / lib / pleroma / captcha / kocaptcha.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Captcha.Kocaptcha do
6 alias Pleroma.Captcha.Service
7 @behaviour Service
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 %{
21 type: :kocaptcha,
22 token: json_resp["token"],
23 url: endpoint <> json_resp["url"],
24 answer_data: json_resp["md5"]
25 }
26 end
27 end
28
29 @impl Service
30 def validate(_token, captcha, answer_data) do
31 # Here the token is unsed, because the unencrypted captcha answer is just passed to method
32 if not is_nil(captcha) and
33 :crypto.hash(:md5, captcha) |> Base.encode16() == String.upcase(answer_data),
34 do: :ok,
35 else: {:error, "Invalid CAPTCHA"}
36 end
37 end