1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
5 defmodule Pleroma.Web.Auth.PleromaAuthenticator do
6 alias Pleroma.Registration
10 import Pleroma.Web.Auth.Helpers, only: [fetch_credentials: 1, fetch_user: 1]
12 @behaviour Pleroma.Web.Auth.Authenticator
14 def get_user(%Plug.Conn{} = conn) do
15 with {:ok, {name, password}} <- fetch_credentials(conn),
16 {_, %User{} = user} <- {:user, fetch_user(name)},
17 {_, true} <- {:checkpw, Pleroma.Password.checkpw(password, user.password_hash)},
18 {:ok, user} <- Pleroma.Password.maybe_update_password(user, password) do
21 {:error, _reason} = error -> error
22 error -> {:error, error}
27 Gets or creates Pleroma.Registration record from Ueberauth assigns.
28 Note: some strategies (like `keycloak`) might need extra configuration to fill `uid` from callback response —
29 see [`docs/config.md`](docs/config.md).
31 def get_registration(%Plug.Conn{assigns: %{ueberauth_auth: %{uid: nil}}}),
32 do: {:error, :missing_uid}
34 def get_registration(%Plug.Conn{
35 assigns: %{ueberauth_auth: %{provider: provider, uid: uid} = auth}
37 registration = Registration.get_by_provider_uid(provider, uid)
45 |> Registration.changeset(%{
46 provider: to_string(provider),
49 "nickname" => info.nickname,
50 "email" => info.email,
52 "description" => info.description
59 def get_registration(%Plug.Conn{} = _conn), do: {:error, :missing_credentials}
61 @doc "Creates Pleroma.User record basing on params and Pleroma.Registration record."
62 @spec create_from_registration(Plug.Conn.t(), Registration.t()) ::
63 {:ok, User.t()} | {:error, any()}
64 def create_from_registration(
65 %Plug.Conn{params: %{"authorization" => registration_attrs}},
66 %Registration{} = registration
68 nickname = value([registration_attrs["nickname"], Registration.nickname(registration)])
69 email = value([registration_attrs["email"], Registration.email(registration)])
70 name = value([registration_attrs["name"], Registration.name(registration)]) || nickname
71 bio = value([registration_attrs["bio"], Registration.description(registration)]) || ""
73 random_password = :crypto.strong_rand_bytes(64) |> Base.encode64()
75 with {:ok, new_user} <-
76 User.register_changeset(
83 password: random_password,
84 password_confirmation: random_password
91 Registration.changeset(registration, %{user_id: new_user.id}) |> Repo.update() do
98 defp value(list), do: Enum.find(list, &(to_string(&1) != ""))
100 def handle_error(%Plug.Conn{} = _conn, error) do
104 def auth_template, do: nil
106 def oauth_consumer_template, do: nil