9ba0f30be5131de0d31aca61a6a60aa7560e6207
[anni] / lib / pleroma / captcha / native.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2022 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Captcha.Native do
6   alias Pleroma.Captcha.Service
7   @behaviour Service
8
9   @impl Service
10   def new do
11     case Captcha.get() do
12       :error ->
13         %{error: :captcha_error}
14
15       {:ok, answer_data, img_binary} ->
16         %{
17           type: :native,
18           token: token(),
19           url: "data:image/png;base64," <> Base.encode64(img_binary),
20           answer_data: answer_data,
21           seconds_valid: Pleroma.Config.get([Pleroma.Captcha, :seconds_valid])
22         }
23     end
24   end
25
26   @impl Service
27   def validate(_token, captcha, captcha) when not is_nil(captcha), do: :ok
28   def validate(_token, _captcha, _answer), do: {:error, :invalid}
29
30   defp token do
31     10
32     |> :crypto.strong_rand_bytes()
33     |> Base.url_encode64(padding: false)
34   end
35 end