Merge remote-tracking branch 'remotes/upstream/develop' into twitter_oauth
[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
9 @behaviour Pleroma.Web.Auth.Authenticator
10
11 def get_user(%Plug.Conn{} = _conn, %{
12 "authorization" => %{"name" => name, "password" => password}
13 }) do
14 with {_, %User{} = user} <- {:user, User.get_by_nickname_or_email(name)},
15 {_, true} <- {:checkpw, Pbkdf2.checkpw(password, user.password_hash)} do
16 {:ok, user}
17 else
18 error ->
19 {:error, error}
20 end
21 end
22
23 def get_user(%Plug.Conn{} = _conn, _params), do: {:error, :missing_credentials}
24
25 def get_or_create_user_by_oauth(
26 %Plug.Conn{assigns: %{ueberauth_auth: %{provider: provider, uid: uid} = auth}},
27 _params
28 ) do
29 user = User.get_by_auth_provider_uid(provider, uid)
30
31 if user do
32 {:ok, user}
33 else
34 info = auth.info
35 email = info.email
36 nickname = info.nickname
37
38 # TODO: FIXME: connect to existing (non-oauth) account (need a UI flow for that) / generate a random nickname?
39 email =
40 if email && User.get_by_email(email) do
41 nil
42 else
43 email
44 end
45
46 nickname =
47 if nickname && User.get_by_nickname(nickname) do
48 nil
49 else
50 nickname
51 end
52
53 new_user =
54 User.oauth_register_changeset(
55 %User{},
56 %{
57 auth_provider: to_string(provider),
58 auth_provider_uid: to_string(uid),
59 name: info.name,
60 bio: info.description,
61 email: email,
62 nickname: nickname
63 }
64 )
65
66 Pleroma.Repo.insert(new_user)
67 end
68 end
69
70 def get_or_create_user_by_oauth(%Plug.Conn{} = _conn, _params),
71 do: {:error, :missing_credentials}
72
73 def handle_error(%Plug.Conn{} = _conn, error) do
74 error
75 end
76
77 def auth_template, do: nil
78 end