Merge branch 'fix/digest-task-otp' into 'develop'
[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 call(%{assigns: %{user: %User{}}} = conn, _), do: conn
34
35 def call(
36 %{
37 assigns: %{
38 auth_user: %{password_hash: password_hash} = auth_user,
39 auth_credentials: %{password: password}
40 }
41 } = conn,
42 _
43 ) do
44 if checkpw(password, password_hash) do
45 conn
46 |> assign(:user, auth_user)
47 |> OAuthScopesPlug.skip_plug()
48 else
49 conn
50 end
51 end
52
53 def call(%{assigns: %{auth_credentials: %{password: _}}} = conn, _) do
54 Pbkdf2.no_user_verify()
55 conn
56 end
57
58 def call(conn, _), do: conn
59 end