1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
5 defmodule Pleroma.Web.Plugs.AuthenticationPlug do
6 @moduledoc "Password authentication plug."
8 alias Pleroma.Helpers.AuthHelper
15 def init(options), do: options
17 def call(%{assigns: %{user: %User{}}} = conn, _), do: conn
22 auth_user: %{password_hash: password_hash} = auth_user,
23 auth_credentials: %{password: password}
28 if checkpw(password, password_hash) do
29 {:ok, auth_user} = maybe_update_password(auth_user, password)
32 |> assign(:user, auth_user)
33 |> AuthHelper.skip_oauth()
39 def call(conn, _), do: conn
41 def checkpw(password, "$6" <> _ = password_hash) do
42 :crypt.crypt(password, password_hash) == password_hash
45 def checkpw(password, "$2" <> _ = password_hash) do
46 # Handle bcrypt passwords for Mastodon migration
47 Bcrypt.verify_pass(password, password_hash)
50 def checkpw(password, "$pbkdf2" <> _ = password_hash) do
51 Pleroma.Password.Pbkdf2.verify_pass(password, password_hash)
54 def checkpw(_password, _password_hash) do
55 Logger.error("Password hash not recognized")
59 def maybe_update_password(%User{password_hash: "$2" <> _} = user, password) do
60 do_update_password(user, password)
63 def maybe_update_password(%User{password_hash: "$6" <> _} = user, password) do
64 do_update_password(user, password)
67 def maybe_update_password(user, _), do: {:ok, user}
69 defp do_update_password(user, password) do
70 User.reset_password(user, %{password: password, password_confirmation: password})