2d4399490abe2889ce68fd45f603b530f2719691
[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 with {:ok, new_user} <-
63 User.external_registration_changeset(
64 %User{},
65 %{
66 name: info.name,
67 bio: info.description,
68 email: email,
69 nickname: nickname
70 }
71 )
72 |> Repo.insert(),
73 {:ok, _} <-
74 Registration.changeset(%Registration{}, %{
75 user_id: new_user.id,
76 provider: to_string(provider),
77 uid: to_string(uid),
78 info: %{nickname: info.nickname, email: info.email}
79 })
80 |> Repo.insert() do
81 {:ok, new_user}
82 end
83 end
84 end
85
86 def get_by_external_registration(%Plug.Conn{} = _conn, _params),
87 do: {:error, :missing_credentials}
88
89 def handle_error(%Plug.Conn{} = _conn, error) do
90 error
91 end
92
93 def auth_template, do: nil
94 end