Refactored Pleroma.Web.Auth.Authenticator
[akkoma] / lib / pleroma / web / auth / authenticator.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Web.Auth.Authenticator do
6 alias Pleroma.Registration
7 alias Pleroma.User
8
9 def implementation do
10 Pleroma.Config.get(
11 Pleroma.Web.Auth.Authenticator,
12 Pleroma.Web.Auth.PleromaAuthenticator
13 )
14 end
15
16 @callback get_user(Plug.Conn.t()) :: {:ok, User.t()} | {:error, any()}
17 def get_user(plug), do: implementation().get_user(plug)
18
19 @callback create_from_registration(Plug.Conn.t(), Registration.t()) ::
20 {:ok, User.t()} | {:error, any()}
21 def create_from_registration(plug, registration),
22 do: implementation().create_from_registration(plug, registration)
23
24 @callback get_registration(Plug.Conn.t()) ::
25 {:ok, Registration.t()} | {:error, any()}
26 def get_registration(plug), do: implementation().get_registration(plug)
27
28 @callback handle_error(Plug.Conn.t(), any()) :: any()
29 def handle_error(plug, error),
30 do: implementation().handle_error(plug, error)
31
32 @callback auth_template() :: String.t() | nil
33 def auth_template do
34 # Note: `config :pleroma, :auth_template, "..."` support is deprecated
35 implementation().auth_template() ||
36 Pleroma.Config.get([:auth, :auth_template], Pleroma.Config.get(:auth_template)) ||
37 "show.html"
38 end
39
40 @callback oauth_consumer_template() :: String.t() | nil
41 def oauth_consumer_template do
42 implementation().oauth_consumer_template() ||
43 Pleroma.Config.get([:auth, :oauth_consumer_template], "consumer.html")
44 end
45
46 @doc "Gets user by nickname or email for auth."
47 @spec fetch_user(String.t()) :: User.t() | nil
48 def fetch_user(name) do
49 User.get_by_nickname_or_email(name)
50 end
51
52 # Gets name and password from conn
53 #
54 @spec fetch_credentials(Plug.Conn.t() | map()) ::
55 {:ok, {name :: any, password :: any}} | {:error, :invalid_credentials}
56 def fetch_credentials(%Plug.Conn{params: params} = _),
57 do: fetch_credentials(params)
58
59 def fetch_credentials(params) do
60 case params do
61 %{"authorization" => %{"name" => name, "password" => password}} ->
62 {:ok, {name, password}}
63
64 %{"grant_type" => "password", "username" => name, "password" => password} ->
65 {:ok, {name, password}}
66
67 _ ->
68 {:error, :invalid_credentials}
69 end
70 end
71 end