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