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