extend reject MRF to check if originating instance is blocked
[akkoma] / lib / pleroma / web / plugs / authentication_plug.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2021 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, "$6" <> _ = password_hash) do
42 :crypt.crypt(password, password_hash) == password_hash
43 end
44
45 def checkpw(password, "$2" <> _ = password_hash) do
46 # Handle bcrypt passwords for Mastodon migration
47 Bcrypt.verify_pass(password, password_hash)
48 end
49
50 def checkpw(password, "$pbkdf2" <> _ = password_hash) do
51 Pleroma.Password.Pbkdf2.verify_pass(password, password_hash)
52 end
53
54 def checkpw(_password, _password_hash) do
55 Logger.error("Password hash not recognized")
56 false
57 end
58
59 def maybe_update_password(%User{password_hash: "$2" <> _} = user, password) do
60 do_update_password(user, password)
61 end
62
63 def maybe_update_password(%User{password_hash: "$6" <> _} = user, password) do
64 do_update_password(user, password)
65 end
66
67 def maybe_update_password(user, _), do: {:ok, user}
68
69 defp do_update_password(user, password) do
70 User.reset_password(user, %{password: password, password_confirmation: password})
71 end
72 end