static-fe overhaul (#236)
[akkoma] / lib / pleroma / mfa / backup_codes.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.MFA.BackupCodes do
6 @moduledoc """
7 This module contains functions for generating backup codes.
8 """
9 alias Pleroma.Config
10
11 @config_ns [:instance, :multi_factor_authentication, :backup_codes]
12
13 @doc """
14 Generates backup codes.
15 """
16 @spec generate(Keyword.t()) :: list(String.t())
17 def generate(opts \\ []) do
18 number_of_codes = Keyword.get(opts, :number_of_codes, default_backup_codes_number())
19 code_length = Keyword.get(opts, :length, default_backup_codes_code_length())
20
21 Enum.map(1..number_of_codes, fn _ ->
22 :crypto.strong_rand_bytes(div(code_length, 2))
23 |> Base.encode16(case: :lower)
24 end)
25 end
26
27 defp default_backup_codes_number, do: Config.get(@config_ns ++ [:number], 5)
28
29 defp default_backup_codes_code_length,
30 do: Config.get(@config_ns ++ [:length], 16)
31 end