Merge branch 'issue/2069' into 'develop'
[akkoma] / lib / pleroma / web / admin_api / controllers / invite_controller.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.AdminAPI.InviteController do
6 use Pleroma.Web, :controller
7
8 import Pleroma.Web.ControllerHelper, only: [json_response: 3]
9
10 alias Pleroma.Config
11 alias Pleroma.UserInviteToken
12 alias Pleroma.Web.Plugs.OAuthScopesPlug
13
14 require Logger
15
16 plug(Pleroma.Web.ApiSpec.CastAndValidate)
17 plug(OAuthScopesPlug, %{scopes: ["read:invites"], admin: true} when action == :index)
18
19 plug(
20 OAuthScopesPlug,
21 %{scopes: ["write:invites"], admin: true} when action in [:create, :revoke, :email]
22 )
23
24 action_fallback(Pleroma.Web.AdminAPI.FallbackController)
25
26 defdelegate open_api_operation(action), to: Pleroma.Web.ApiSpec.Admin.InviteOperation
27
28 @doc "Get list of created invites"
29 def index(conn, _params) do
30 invites = UserInviteToken.list_invites()
31
32 render(conn, "index.json", invites: invites)
33 end
34
35 @doc "Create an account registration invite token"
36 def create(%{body_params: params} = conn, _) do
37 {:ok, invite} = UserInviteToken.create_invite(params)
38
39 render(conn, "show.json", invite: invite)
40 end
41
42 @doc "Revokes invite by token"
43 def revoke(%{body_params: %{token: token}} = conn, _) do
44 with {:ok, invite} <- UserInviteToken.find_by_token(token),
45 {:ok, updated_invite} = UserInviteToken.update_invite(invite, %{used: true}) do
46 render(conn, "show.json", invite: updated_invite)
47 else
48 nil -> {:error, :not_found}
49 error -> error
50 end
51 end
52
53 @doc "Sends registration invite via email"
54 def email(%{assigns: %{user: user}, body_params: %{email: email} = params} = conn, _) do
55 with {_, false} <- {:registrations_open, Config.get([:instance, :registrations_open])},
56 {_, true} <- {:invites_enabled, Config.get([:instance, :invites_enabled])},
57 {:ok, invite_token} <- UserInviteToken.create_invite(),
58 {:ok, _} <-
59 user
60 |> Pleroma.Emails.UserEmail.user_invitation_email(
61 invite_token,
62 email,
63 params[:name]
64 )
65 |> Pleroma.Emails.Mailer.deliver() do
66 json_response(conn, :no_content, "")
67 else
68 {:registrations_open, _} ->
69 {:error, "To send invites you need to set the `registrations_open` option to false."}
70
71 {:invites_enabled, _} ->
72 {:error, "To send invites you need to set the `invites_enabled` option to true."}
73
74 {:error, error} ->
75 {:error, error}
76 end
77 end
78 end