Merge branch 'release/2.4.0' into 'stable'
[akkoma] / lib / pleroma / web / mastodon_api / controllers / follow_request_controller.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Web.MastodonAPI.FollowRequestController do
6 use Pleroma.Web, :controller
7
8 alias Pleroma.User
9 alias Pleroma.Web.CommonAPI
10 alias Pleroma.Web.Plugs.OAuthScopesPlug
11
12 plug(Pleroma.Web.ApiSpec.CastAndValidate)
13 plug(:assign_follower when action != :index)
14
15 action_fallback(:errors)
16
17 plug(OAuthScopesPlug, %{scopes: ["follow", "read:follows"]} when action == :index)
18
19 plug(
20 OAuthScopesPlug,
21 %{scopes: ["follow", "write:follows"]} when action != :index
22 )
23
24 defdelegate open_api_operation(action), to: Pleroma.Web.ApiSpec.FollowRequestOperation
25
26 @doc "GET /api/v1/follow_requests"
27 def index(%{assigns: %{user: followed}} = conn, _params) do
28 follow_requests = User.get_follow_requests(followed)
29
30 render(conn, "index.json", for: followed, users: follow_requests, as: :user)
31 end
32
33 @doc "POST /api/v1/follow_requests/:id/authorize"
34 def authorize(%{assigns: %{user: followed, follower: follower}} = conn, _params) do
35 with {:ok, follower} <- CommonAPI.accept_follow_request(follower, followed) do
36 render(conn, "relationship.json", user: followed, target: follower)
37 end
38 end
39
40 @doc "POST /api/v1/follow_requests/:id/reject"
41 def reject(%{assigns: %{user: followed, follower: follower}} = conn, _params) do
42 with {:ok, follower} <- CommonAPI.reject_follow_request(follower, followed) do
43 render(conn, "relationship.json", user: followed, target: follower)
44 end
45 end
46
47 defp assign_follower(%{params: %{id: id}} = conn, _) do
48 case User.get_cached_by_id(id) do
49 %User{} = follower -> assign(conn, :follower, follower)
50 nil -> Pleroma.Web.MastodonAPI.FallbackController.call(conn, {:error, :not_found}) |> halt()
51 end
52 end
53
54 defp errors(conn, {:error, message}) do
55 conn
56 |> put_status(:forbidden)
57 |> json(%{error: message})
58 end
59 end