Merge remote-tracking branch 'pleroma/develop' into feature/disable-account
[akkoma] / lib / pleroma / web / auth / pleroma_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.PleromaAuthenticator do
6 alias Comeonin.Pbkdf2
7 alias Pleroma.Registration
8 alias Pleroma.Repo
9 alias Pleroma.User
10
11 import Pleroma.Web.Auth.Authenticator,
12 only: [fetch_credentials: 1, fetch_user: 1]
13
14 @behaviour Pleroma.Web.Auth.Authenticator
15
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
20 {:ok, user}
21 else
22 error ->
23 {:error, error}
24 end
25 end
26
27 def get_registration(%Plug.Conn{
28 assigns: %{ueberauth_auth: %{provider: provider, uid: uid} = auth}
29 }) do
30 registration = Registration.get_by_provider_uid(provider, uid)
31
32 if registration do
33 {:ok, registration}
34 else
35 info = auth.info
36
37 %Registration{}
38 |> Registration.changeset(%{
39 provider: to_string(provider),
40 uid: to_string(uid),
41 info: %{
42 "nickname" => info.nickname,
43 "email" => info.email,
44 "name" => info.name,
45 "description" => info.description
46 }
47 })
48 |> Repo.insert()
49 end
50 end
51
52 def get_registration(%Plug.Conn{} = _conn), do: {:error, :missing_credentials}
53
54 def create_from_registration(
55 %Plug.Conn{params: %{"authorization" => registration_attrs}},
56 registration
57 ) do
58 nickname = value([registration_attrs["nickname"], Registration.nickname(registration)])
59 email = value([registration_attrs["email"], Registration.email(registration)])
60 name = value([registration_attrs["name"], Registration.name(registration)]) || nickname
61 bio = value([registration_attrs["bio"], Registration.description(registration)])
62
63 random_password = :crypto.strong_rand_bytes(64) |> Base.encode64()
64
65 with {:ok, new_user} <-
66 User.register_changeset(
67 %User{},
68 %{
69 email: email,
70 nickname: nickname,
71 name: name,
72 bio: bio,
73 password: random_password,
74 password_confirmation: random_password
75 },
76 external: true,
77 confirmed: true
78 )
79 |> Repo.insert(),
80 {:ok, _} <-
81 Registration.changeset(registration, %{user_id: new_user.id}) |> Repo.update() do
82 {:ok, new_user}
83 end
84 end
85
86 defp value(list), do: Enum.find(list, &(to_string(&1) != ""))
87
88 def handle_error(%Plug.Conn{} = _conn, error) do
89 error
90 end
91
92 def auth_template, do: nil
93
94 def oauth_consumer_template, do: nil
95 end