revert ae54c06bb4bd2389d6eb1502b842c6b632e12e40
[akkoma] / lib / pleroma / password.ex
1 defmodule Pleroma.Password do
2 @moduledoc """
3 This module handles password hashing and verification.
4 It will delegate to the appropriate module based on the password hash.
5 It also handles upgrading of password hashes.
6 """
7
8 alias Pleroma.User
9 alias Pleroma.Password.Pbkdf2
10 require Logger
11
12 @hashing_module Argon2
13
14 @spec hash_pwd_salt(String.t()) :: String.t()
15 defdelegate hash_pwd_salt(pass), to: @hashing_module
16
17 @spec checkpw(String.t(), String.t()) :: boolean()
18 def checkpw(password, "$2" <> _ = password_hash) do
19 # Handle bcrypt passwords for Mastodon migration
20 Bcrypt.verify_pass(password, password_hash)
21 end
22
23 def checkpw(password, "$pbkdf2" <> _ = password_hash) do
24 Pbkdf2.verify_pass(password, password_hash)
25 end
26
27 def checkpw(password, "$argon2" <> _ = password_hash) do
28 Argon2.verify_pass(password, password_hash)
29 end
30
31 def checkpw(_password, _password_hash) do
32 Logger.error("Password hash not recognized")
33 false
34 end
35
36 @spec maybe_update_password(User.t(), String.t()) ::
37 {:ok, User.t()} | {:error, Ecto.Changeset.t()}
38 def maybe_update_password(%User{password_hash: "$2" <> _} = user, password) do
39 do_update_password(user, password)
40 end
41
42 def maybe_update_password(%User{password_hash: "$6" <> _} = user, password) do
43 do_update_password(user, password)
44 end
45
46 def maybe_update_password(%User{password_hash: "$pbkdf2" <> _} = user, password) do
47 do_update_password(user, password)
48 end
49
50 def maybe_update_password(user, _), do: {:ok, user}
51
52 defp do_update_password(user, password) do
53 User.reset_password(user, %{password: password, password_confirmation: password})
54 end
55 end