move to 2.5.5
[anni] / test / pleroma / web / auth / totp_authenticator_test.exs
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.Web.Auth.TOTPAuthenticatorTest do
6   use Pleroma.Web.ConnCase, async: true
7
8   alias Pleroma.MFA
9   alias Pleroma.MFA.BackupCodes
10   alias Pleroma.MFA.TOTP
11   alias Pleroma.Web.Auth.TOTPAuthenticator
12
13   import Pleroma.Factory
14
15   test "verify token" do
16     otp_secret = TOTP.generate_secret()
17     otp_token = TOTP.generate_token(otp_secret)
18
19     user =
20       insert(:user,
21         multi_factor_authentication_settings: %MFA.Settings{
22           enabled: true,
23           totp: %MFA.Settings.TOTP{secret: otp_secret, confirmed: true}
24         }
25       )
26
27     assert TOTPAuthenticator.verify(otp_token, user) == {:ok, :pass}
28     assert TOTPAuthenticator.verify(nil, user) == {:error, :invalid_token}
29     assert TOTPAuthenticator.verify("", user) == {:error, :invalid_token}
30   end
31
32   test "checks backup codes" do
33     [code | _] = backup_codes = BackupCodes.generate()
34
35     hashed_codes =
36       backup_codes
37       |> Enum.map(&Pleroma.Password.Pbkdf2.hash_pwd_salt(&1))
38
39     user =
40       insert(:user,
41         multi_factor_authentication_settings: %MFA.Settings{
42           enabled: true,
43           backup_codes: hashed_codes,
44           totp: %MFA.Settings.TOTP{secret: "otp_secret", confirmed: true}
45         }
46       )
47
48     assert TOTPAuthenticator.verify_recovery_code(user, code) == {:ok, :pass}
49     refute TOTPAuthenticator.verify_recovery_code(code, refresh_record(user)) == {:ok, :pass}
50   end
51 end