1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
5 defmodule Pleroma.Web.Auth.PleromaAuthenticator do
6 alias Pleroma.Plugs.AuthenticationPlug
7 alias Pleroma.Registration
11 import Pleroma.Web.Auth.Authenticator,
12 only: [fetch_credentials: 1, fetch_user: 1]
14 @behaviour Pleroma.Web.Auth.Authenticator
16 def get_user(%Plug.Conn{} = conn) do
17 with {:ok, {name, password}} <- fetch_credentials(conn),
18 {_, %User{} = user} <- {:user, fetch_user(name)},
19 {_, true} <- {:checkpw, AuthenticationPlug.checkpw(password, user.password_hash)},
20 {:ok, user} <- AuthenticationPlug.maybe_update_password(user, password) do
23 {:error, _reason} = error -> error
24 error -> {:error, error}
29 Gets or creates Pleroma.Registration record from Ueberauth assigns.
30 Note: some strategies (like `keycloak`) might need extra configuration to fill `uid` from callback response —
31 see [`docs/config.md`](docs/config.md).
33 def get_registration(%Plug.Conn{assigns: %{ueberauth_auth: %{uid: nil}}}),
34 do: {:error, :missing_uid}
36 def get_registration(%Plug.Conn{
37 assigns: %{ueberauth_auth: %{provider: provider, uid: uid} = auth}
39 registration = Registration.get_by_provider_uid(provider, uid)
47 |> Registration.changeset(%{
48 provider: to_string(provider),
51 "nickname" => info.nickname,
52 "email" => info.email,
54 "description" => info.description
61 def get_registration(%Plug.Conn{} = _conn), do: {:error, :missing_credentials}
63 @doc "Creates Pleroma.User record basing on params and Pleroma.Registration record."
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
87 need_confirmation: false
91 Registration.changeset(registration, %{user_id: new_user.id}) |> Repo.update() do
96 defp value(list), do: Enum.find(list, &(to_string(&1) != ""))
98 def handle_error(%Plug.Conn{} = _conn, error) do
102 def auth_template, do: nil
104 def oauth_consumer_template, do: nil