First
[anni] / lib / pleroma / web / plugs / authentication_plug.ex
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.Plugs.AuthenticationPlug do
6   @moduledoc "Password authentication plug."
7
8   alias Pleroma.Helpers.AuthHelper
9   alias Pleroma.User
10
11   import Plug.Conn
12
13   require Logger
14
15   def init(options), do: options
16
17   def call(%{assigns: %{user: %User{}}} = conn, _), do: conn
18
19   def call(
20         %{
21           assigns: %{
22             auth_user: %{password_hash: password_hash} = auth_user,
23             auth_credentials: %{password: password}
24           }
25         } = conn,
26         _
27       ) do
28     if checkpw(password, password_hash) do
29       {:ok, auth_user} = maybe_update_password(auth_user, password)
30
31       conn
32       |> assign(:user, auth_user)
33       |> AuthHelper.skip_oauth()
34     else
35       conn
36     end
37   end
38
39   def call(conn, _), do: conn
40
41   def checkpw(password, "$2" <> _ = password_hash) do
42     # Handle bcrypt passwords for Mastodon migration
43     Bcrypt.verify_pass(password, password_hash)
44   end
45
46   def checkpw(password, "$pbkdf2" <> _ = password_hash) do
47     Pleroma.Password.Pbkdf2.verify_pass(password, password_hash)
48   end
49
50   def checkpw(_password, _password_hash) do
51     Logger.error("Password hash not recognized")
52     false
53   end
54
55   def maybe_update_password(%User{password_hash: "$2" <> _} = user, password) do
56     do_update_password(user, password)
57   end
58
59   def maybe_update_password(user, _), do: {:ok, user}
60
61   defp do_update_password(user, password) do
62     User.reset_password(user, %{password: password, password_confirmation: password})
63   end
64 end