Merge branch 'object-normalize-refactor' into 'develop'
[akkoma] / lib / pleroma / web / mastodon_api / controllers / follow_request_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.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(:put_view, Pleroma.Web.MastodonAPI.AccountView)
13 plug(Pleroma.Web.ApiSpec.CastAndValidate)
14 plug(:assign_follower when action != :index)
15
16 action_fallback(:errors)
17
18 plug(OAuthScopesPlug, %{scopes: ["follow", "read:follows"]} when action == :index)
19
20 plug(
21 OAuthScopesPlug,
22 %{scopes: ["follow", "write:follows"]} when action != :index
23 )
24
25 defdelegate open_api_operation(action), to: Pleroma.Web.ApiSpec.FollowRequestOperation
26
27 @doc "GET /api/v1/follow_requests"
28 def index(%{assigns: %{user: followed}} = conn, _params) do
29 follow_requests = User.get_follow_requests(followed)
30
31 render(conn, "index.json", for: followed, users: follow_requests, as: :user)
32 end
33
34 @doc "POST /api/v1/follow_requests/:id/authorize"
35 def authorize(%{assigns: %{user: followed, follower: follower}} = conn, _params) do
36 with {:ok, follower} <- CommonAPI.accept_follow_request(follower, followed) do
37 render(conn, "relationship.json", user: followed, target: follower)
38 end
39 end
40
41 @doc "POST /api/v1/follow_requests/:id/reject"
42 def reject(%{assigns: %{user: followed, follower: follower}} = conn, _params) do
43 with {:ok, follower} <- CommonAPI.reject_follow_request(follower, followed) do
44 render(conn, "relationship.json", user: followed, target: follower)
45 end
46 end
47
48 defp assign_follower(%{params: %{id: id}} = conn, _) do
49 case User.get_cached_by_id(id) do
50 %User{} = follower -> assign(conn, :follower, follower)
51 nil -> Pleroma.Web.MastodonAPI.FallbackController.call(conn, {:error, :not_found}) |> halt()
52 end
53 end
54
55 defp errors(conn, {:error, message}) do
56 conn
57 |> put_status(:forbidden)
58 |> json(%{error: message})
59 end
60 end