logo

pleroma

My custom branche(s) on git.pleroma.social/pleroma/pleroma git clone https://hacktivis.me/git/pleroma.git

totp_authenticator.ex (1426B)


  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. defmodule Pleroma.Web.Auth.TOTPAuthenticator do
  5. alias Pleroma.MFA
  6. alias Pleroma.MFA.TOTP
  7. alias Pleroma.User
  8. alias Pleroma.Web.Plugs.AuthenticationPlug
  9. @doc "Verify code or check backup code."
  10. @spec verify(String.t(), User.t()) ::
  11. {:ok, :pass} | {:error, :invalid_token | :invalid_secret_and_token}
  12. def verify(
  13. token,
  14. %User{
  15. multi_factor_authentication_settings:
  16. %{enabled: true, totp: %{secret: secret, confirmed: true}} = _
  17. } = _user
  18. )
  19. when is_binary(token) and byte_size(token) > 0 do
  20. TOTP.validate_token(secret, token)
  21. end
  22. def verify(_, _), do: {:error, :invalid_token}
  23. @spec verify_recovery_code(User.t(), String.t()) ::
  24. {:ok, :pass} | {:error, :invalid_token}
  25. def verify_recovery_code(
  26. %User{multi_factor_authentication_settings: %{enabled: true, backup_codes: codes}} = user,
  27. code
  28. )
  29. when is_list(codes) and is_binary(code) do
  30. hash_code = Enum.find(codes, fn hash -> AuthenticationPlug.checkpw(code, hash) end)
  31. if hash_code do
  32. MFA.invalidate_backup_code(user, hash_code)
  33. {:ok, :pass}
  34. else
  35. {:error, :invalid_token}
  36. end
  37. end
  38. def verify_recovery_code(_, _), do: {:error, :invalid_token}
  39. end