Add spec for AccountController.create
[akkoma] / lib / pleroma / web / twitter_api / twitter_api.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Web.TwitterAPI.TwitterAPI do
6 alias Pleroma.Emails.Mailer
7 alias Pleroma.Emails.UserEmail
8 alias Pleroma.Repo
9 alias Pleroma.User
10 alias Pleroma.UserInviteToken
11
12 require Pleroma.Constants
13
14 def register_user(params, opts \\ []) do
15 params =
16 params
17 |> Map.take([
18 :nickname,
19 :password,
20 :captcha_solution,
21 :captcha_token,
22 :captcha_answer_data,
23 :token,
24 :email
25 ])
26 |> Map.put(:bio, User.parse_bio(params[:bio] || ""))
27 |> Map.put(:name, params.fullname)
28 |> Map.put(:password_confirmation, params[:confirm])
29
30 case validate_captcha(params) do
31 :ok ->
32 if Pleroma.Config.get([:instance, :registrations_open]) do
33 create_user(params, opts)
34 else
35 create_user_with_invite(params, opts)
36 end
37
38 {:error, error} ->
39 # I have no idea how this error handling works
40 {:error, %{error: Jason.encode!(%{captcha: [error]})}}
41 end
42 end
43
44 defp validate_captcha(params) do
45 if Pleroma.Config.get([Pleroma.Captcha, :enabled]) do
46 Pleroma.Captcha.validate(
47 params.captcha_token,
48 params.captcha_solution,
49 params.captcha_answer_data
50 )
51 else
52 :ok
53 end
54 end
55
56 defp create_user_with_invite(params, opts) do
57 with %{token: token} when is_binary(token) <- params,
58 %UserInviteToken{} = invite <- Repo.get_by(UserInviteToken, %{token: token}),
59 true <- UserInviteToken.valid_invite?(invite) do
60 UserInviteToken.update_usage!(invite)
61 create_user(params, opts)
62 else
63 nil -> {:error, "Invalid token"}
64 _ -> {:error, "Expired token"}
65 end
66 end
67
68 defp create_user(params, opts) do
69 changeset = User.register_changeset(%User{}, params, opts)
70
71 case User.register(changeset) do
72 {:ok, user} ->
73 {:ok, user}
74
75 {:error, changeset} ->
76 errors =
77 Ecto.Changeset.traverse_errors(changeset, fn {msg, _opts} -> msg end)
78 |> Jason.encode!()
79
80 {:error, %{error: errors}}
81 end
82 end
83
84 def password_reset(nickname_or_email) do
85 with true <- is_binary(nickname_or_email),
86 %User{local: true, email: email} = user when not is_nil(email) <-
87 User.get_by_nickname_or_email(nickname_or_email),
88 {:ok, token_record} <- Pleroma.PasswordResetToken.create_token(user) do
89 user
90 |> UserEmail.password_reset_email(token_record.token)
91 |> Mailer.deliver_async()
92
93 {:ok, :enqueued}
94 else
95 false ->
96 {:error, "bad user identifier"}
97
98 %User{local: true, email: nil} ->
99 {:ok, :noop}
100
101 %User{local: false} ->
102 {:error, "remote user"}
103
104 nil ->
105 {:error, "unknown user"}
106 end
107 end
108 end