From baa118a74f4ce6c97af37c449a1c5b65195e3d75 Mon Sep 17 00:00:00 2001 From: FloatingGhost Date: Fri, 30 Dec 2022 02:05:16 +0000 Subject: [PATCH] Collect password functions in a module --- lib/pleroma/password.ex | 51 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 lib/pleroma/password.ex diff --git a/lib/pleroma/password.ex b/lib/pleroma/password.ex new file mode 100644 index 000000000..4bf817bee --- /dev/null +++ b/lib/pleroma/password.ex @@ -0,0 +1,51 @@ +defmodule Pleroma.Password do + @moduledoc """ + This module handles password hashing and verification. + It will delegate to the appropriate module based on the password hash. + It also handles upgrading of password hashes. + """ + + alias Pleroma.User + alias Pleroma.Password.Pbkdf2 + + @hashing_module Argon2 + + defdelegate hash_pwd_salt, to: @hashing_module + + @spec checkpw(String.t(), String.t()) :: boolean() + def checkpw(password, "$2" <> _ = password_hash) do + # Handle bcrypt passwords for Mastodon migration + Bcrypt.verify_pass(password, password_hash) + end + + def checkpw(password, "$pbkdf2" <> _ = password_hash) do + Pbkdf2.verify_pass(password, password_hash) + end + + def checkpw(password, "$argon2" <> _ = password_hash) do + Argon2.verify_pass(password, password_hash) + end + + def checkpw(_password, _password_hash) do + Logger.error("Password hash not recognized") + false + end + + def maybe_update_password(%User{password_hash: "$2" <> _} = user, password) do + do_update_password(user, password) + end + + def maybe_update_password(%User{password_hash: "$6" <> _} = user, password) do + do_update_password(user, password) + end + + def maybe_update_password(%User{password_hash: "$pbkdf2" <> _} = user, password) do + do_update_password(user, password) + end + + def maybe_update_password(user, _), do: {:ok, user} + + defp do_update_password(user, password) do + User.reset_password(user, %{password: password, password_confirmation: password}) + end +end