Merge branch 'develop' of https://git.pleroma.social/pleroma/pleroma into develop
[akkoma] / lib / pleroma / web / auth / authenticator.ex
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
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()) :: {:ok, Registration.t()} | {:error, any()}
25 def get_registration(plug), do: implementation().get_registration(plug)
26
27 @callback handle_error(Plug.Conn.t(), any()) :: any()
28 def handle_error(plug, error),
29 do: implementation().handle_error(plug, error)
30
31 @callback auth_template() :: String.t() | nil
32 def auth_template do
33 # Note: `config :pleroma, :auth_template, "..."` support is deprecated
34 implementation().auth_template() ||
35 Pleroma.Config.get([:auth, :auth_template], Pleroma.Config.get(:auth_template)) ||
36 "show.html"
37 end
38
39 @callback oauth_consumer_template() :: String.t() | nil
40 def oauth_consumer_template do
41 implementation().oauth_consumer_template() ||
42 Pleroma.Config.get([:auth, :oauth_consumer_template], "consumer.html")
43 end
44
45 @doc "Gets user by nickname or email for auth."
46 @spec fetch_user(String.t()) :: User.t() | nil
47 def fetch_user(name) do
48 User.get_by_nickname_or_email(name)
49 end
50
51 # Gets name and password from conn
52 #
53 @spec fetch_credentials(Plug.Conn.t() | map()) ::
54 {:ok, {name :: any, password :: any}} | {:error, :invalid_credentials}
55 def fetch_credentials(%Plug.Conn{params: params} = _),
56 do: fetch_credentials(params)
57
58 def fetch_credentials(params) do
59 case params do
60 %{"authorization" => %{"name" => name, "password" => password}} ->
61 {:ok, {name, password}}
62
63 %{"grant_type" => "password", "username" => name, "password" => password} ->
64 {:ok, {name, password}}
65
66 _ ->
67 {:error, :invalid_credentials}
68 end
69 end
70 end