Add unit test for Pleroma API app controller
[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.Maps
14 alias Pleroma.User
15 alias Pleroma.Repo
16 alias Pleroma.Web.OAuth.App
17 alias Pleroma.Web.OAuth.Scopes
18 alias Pleroma.Web.OAuth.Token
19
20 require Logger
21
22 action_fallback(Pleroma.Web.MastodonAPI.FallbackController)
23
24 plug(:skip_auth when action in [:create, :verify_credentials])
25
26 plug(Pleroma.Web.ApiSpec.CastAndValidate)
27
28 @local_mastodon_name "Mastodon-Local"
29
30 defdelegate open_api_operation(action), to: Pleroma.Web.ApiSpec.AppOperation
31
32 @doc "POST /api/v1/apps"
33 def create(%{assigns: %{user: user}, body_params: params} = conn, _params) do
34 scopes = Scopes.fetch_scopes(params, ["read"])
35
36 user_id =
37 with %User{id: id} <- user do
38 id
39 else
40 _ -> nil
41 end
42
43 app_attrs =
44 params
45 |> Map.take([:client_name, :redirect_uris, :website])
46 |> Map.put(:scopes, scopes)
47 |> Maps.put_if_present(:user_id, user_id)
48
49 with cs <- App.register_changeset(%App{}, app_attrs),
50 false <- cs.changes[:client_name] == @local_mastodon_name,
51 {:ok, app} <- Repo.insert(cs) do
52 render(conn, "show.json", app: app)
53 end
54 end
55
56 @doc """
57 GET /api/v1/apps/verify_credentials
58 Gets compact non-secret representation of the app. Supports app tokens and user tokens.
59 """
60 def verify_credentials(%{assigns: %{token: %Token{} = token}} = conn, _) do
61 with %{app: %App{} = app} <- Repo.preload(token, :app) do
62 render(conn, "compact_non_secret.json", app: app)
63 end
64 end
65 end