e44c4340ef808eb08cc33272798020c791d717eb
[akkoma] / lib / pleroma / web / mastodon_api / controllers / app_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.AppController do
6 @moduledoc """
7 Controller for supporting app-related actions.
8 If authentication is an option, app tokens (user-unbound) must be supported.
9 """
10
11 use Pleroma.Web, :controller
12
13 alias Pleroma.Repo
14 alias Pleroma.Web.OAuth.App
15 alias Pleroma.Web.OAuth.Scopes
16 alias Pleroma.Web.OAuth.Token
17 alias Pleroma.Web.Plugs.OAuthScopesPlug
18
19 action_fallback(Pleroma.Web.MastodonAPI.FallbackController)
20
21 plug(:skip_auth when action in [:create, :verify_credentials])
22
23 plug(OAuthScopesPlug, %{scopes: ["follow", "read"]} when action in [:index])
24
25 plug(Pleroma.Web.ApiSpec.CastAndValidate)
26
27 @local_mastodon_name "Mastodon-Local"
28
29 defdelegate open_api_operation(action), to: Pleroma.Web.ApiSpec.AppOperation
30
31 @doc "GET /api/v1/apps"
32 def index(%{assigns: %{user: user}} = conn, _params) do
33 with apps <- App.get_user_apps(user) do
34 render(conn, "index.json", %{apps: apps})
35 end
36 end
37
38 @doc "POST /api/v1/apps"
39 def create(%{body_params: params} = conn, _params) do
40 scopes = Scopes.fetch_scopes(params, ["read"])
41
42 app_attrs =
43 params
44 |> Map.take([:client_name, :redirect_uris, :website])
45 |> Map.put(:scopes, scopes)
46
47 with cs <- App.register_changeset(%App{}, app_attrs),
48 false <- cs.changes[:client_name] == @local_mastodon_name,
49 {:ok, app} <- Repo.insert(cs) do
50 render(conn, "show.json", app: app)
51 end
52 end
53
54 @doc """
55 GET /api/v1/apps/verify_credentials
56 Gets compact non-secret representation of the app. Supports app tokens and user tokens.
57 """
58 def verify_credentials(%{assigns: %{token: %Token{} = token}} = conn, _) do
59 with %{app: %App{} = app} <- Repo.preload(token, :app) do
60 render(conn, "compact_non_secret.json", app: app)
61 end
62 end
63 end