36ecd05608d67456b0cc3cfac3dee71379a9ac6e
[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.User
8 alias Pleroma.Registration
9 alias Pleroma.Repo
10
11 @behaviour Pleroma.Web.Auth.Authenticator
12
13 def get_user(%Plug.Conn{} = _conn, params) do
14 {name, password} =
15 case 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_by_external_registration(
33 %Plug.Conn{assigns: %{ueberauth_auth: %{provider: provider, uid: uid} = auth}},
34 _params
35 ) do
36 registration = Registration.get_by_provider_uid(provider, uid)
37
38 if registration do
39 user = Repo.preload(registration, :user).user
40 {:ok, user}
41 else
42 info = auth.info
43 email = info.email
44 nickname = info.nickname
45
46 # Note: nullifying email in case this email is already taken
47 email =
48 if email && User.get_by_email(email) do
49 nil
50 else
51 email
52 end
53
54 # Note: generating a random numeric suffix to nickname in case this nickname is already taken
55 nickname =
56 if nickname && User.get_by_nickname(nickname) do
57 "#{nickname}#{:os.system_time()}"
58 else
59 nickname
60 end
61
62 random_password = :crypto.strong_rand_bytes(64) |> Base.encode64()
63
64 with {:ok, new_user} <-
65 User.register_changeset(
66 %User{},
67 %{
68 name: info.name,
69 bio: info.description,
70 email: email,
71 nickname: nickname,
72 password: random_password,
73 password_confirmation: random_password
74 },
75 external: true,
76 confirmed: true
77 )
78 |> Repo.insert(),
79 {:ok, _} <-
80 Registration.changeset(%Registration{}, %{
81 user_id: new_user.id,
82 provider: to_string(provider),
83 uid: to_string(uid),
84 info: %{nickname: info.nickname, email: info.email}
85 })
86 |> Repo.insert() do
87 {:ok, new_user}
88 end
89 end
90 end
91
92 def get_by_external_registration(%Plug.Conn{} = _conn, _params),
93 do: {:error, :missing_credentials}
94
95 def handle_error(%Plug.Conn{} = _conn, error) do
96 error
97 end
98
99 def auth_template, do: nil
100 end