[#923] Deps config adjustment (no `override` for `httpoison`), code analysis issues...
[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, 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_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 {:ok, registration}
40 else
41 info = auth.info
42
43 Registration.changeset(%Registration{}, %{
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, _params), do: {:error, :missing_credentials}
58
59 def create_from_registration(_conn, params, registration) do
60 nickname = value([params["nickname"], Registration.nickname(registration)])
61 email = value([params["email"], Registration.email(registration)])
62 name = value([params["name"], Registration.name(registration)]) || nickname
63 bio = value([params["bio"], Registration.description(registration)])
64
65 random_password = :crypto.strong_rand_bytes(64) |> Base.encode64()
66
67 with {:ok, new_user} <-
68 User.register_changeset(
69 %User{},
70 %{
71 email: email,
72 nickname: nickname,
73 name: name,
74 bio: bio,
75 password: random_password,
76 password_confirmation: random_password
77 },
78 external: true,
79 confirmed: true
80 )
81 |> Repo.insert(),
82 {:ok, _} <-
83 Registration.changeset(registration, %{user_id: new_user.id}) |> Repo.update() do
84 {:ok, new_user}
85 end
86 end
87
88 defp value(list), do: Enum.find(list, &(to_string(&1) != ""))
89
90 def handle_error(%Plug.Conn{} = _conn, error) do
91 error
92 end
93
94 def auth_template, do: nil
95
96 def oauth_consumer_template, do: nil
97 end