logo

pleroma

My custom branche(s) on git.pleroma.social/pleroma/pleroma

authentication_plug.ex (2020B)


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