1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
5 defmodule Pleroma.Web.Auth.PleromaAuthenticator do
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, Pbkdf2.checkpw(password, user.password_hash)} do
28 Gets or creates Pleroma.Registration record from Ueberauth assigns.
29 Note: some strategies (like `keycloak`) might need extra configuration to fill `uid` from callback response —
30 see [`docs/config.md`](docs/config.md).
32 def get_registration(%Plug.Conn{assigns: %{ueberauth_auth: %{uid: nil}}}),
33 do: {:error, :missing_uid}
35 def get_registration(%Plug.Conn{
36 assigns: %{ueberauth_auth: %{provider: provider, uid: uid} = auth}
38 registration = Registration.get_by_provider_uid(provider, uid)
46 |> Registration.changeset(%{
47 provider: to_string(provider),
50 "nickname" => info.nickname,
51 "email" => info.email,
53 "description" => info.description
60 def get_registration(%Plug.Conn{} = _conn), do: {:error, :missing_credentials}
62 @doc "Creates Pleroma.User record basing on params and Pleroma.Registration record."
63 def create_from_registration(
64 %Plug.Conn{params: %{"authorization" => registration_attrs}},
65 %Registration{} = registration
67 nickname = value([registration_attrs["nickname"], Registration.nickname(registration)])
68 email = value([registration_attrs["email"], Registration.email(registration)])
69 name = value([registration_attrs["name"], Registration.name(registration)]) || nickname
70 bio = value([registration_attrs["bio"], Registration.description(registration)])
72 random_password = :crypto.strong_rand_bytes(64) |> Base.encode64()
74 with {:ok, new_user} <-
75 User.register_changeset(
82 password: random_password,
83 password_confirmation: random_password
86 need_confirmation: false
90 Registration.changeset(registration, %{user_id: new_user.id}) |> Repo.update() do
95 defp value(list), do: Enum.find(list, &(to_string(&1) != ""))
97 def handle_error(%Plug.Conn{} = _conn, error) do
101 def auth_template, do: nil
103 def oauth_consumer_template, do: nil