Authentication Plug: Update bcrypt password on login.
[akkoma] / lib / pleroma / plugs / authentication_plug.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Plugs.AuthenticationPlug do
6 alias Pleroma.Plugs.OAuthScopesPlug
7 alias Pleroma.User
8
9 import Plug.Conn
10
11 require Logger
12
13 def init(options), do: options
14
15 def checkpw(password, "$6" <> _ = password_hash) do
16 :crypt.crypt(password, password_hash) == password_hash
17 end
18
19 def checkpw(password, "$2" <> _ = password_hash) do
20 # Handle bcrypt passwords for Mastodon migration
21 Bcrypt.verify_pass(password, password_hash)
22 end
23
24 def checkpw(password, "$pbkdf2" <> _ = password_hash) do
25 Pbkdf2.verify_pass(password, password_hash)
26 end
27
28 def checkpw(_password, _password_hash) do
29 Logger.error("Password hash not recognized")
30 false
31 end
32
33 def maybe_update_password(%User{password_hash: "$2" <> _} = user, password) do
34 user
35 |> User.password_update_changeset(%{
36 "password" => password,
37 "password_confirmation" => password
38 })
39 |> Pleroma.Repo.update()
40 end
41
42 def maybe_update_password(user, _), do: {:ok, user}
43
44 def call(%{assigns: %{user: %User{}}} = conn, _), do: conn
45
46 def call(
47 %{
48 assigns: %{
49 auth_user: %{password_hash: password_hash} = auth_user,
50 auth_credentials: %{password: password}
51 }
52 } = conn,
53 _
54 ) do
55 if checkpw(password, password_hash) do
56 {:ok, auth_user} = maybe_update_password(auth_user, password)
57
58 conn
59 |> assign(:user, auth_user)
60 |> OAuthScopesPlug.skip_plug()
61 else
62 conn
63 end
64 end
65
66 def call(%{assigns: %{auth_credentials: %{password: _}}} = conn, _) do
67 Pbkdf2.no_user_verify()
68 conn
69 end
70
71 def call(conn, _), do: conn
72 end