oauth_app_controller.ex 2.03 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# Pleroma: A lightweight social networking server
# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
# SPDX-License-Identifier: AGPL-3.0-only

defmodule Pleroma.Web.AdminAPI.OAuthAppController do
  use Pleroma.Web, :controller

  import Pleroma.Web.ControllerHelper, only: [json_response: 3]

  alias Pleroma.Plugs.OAuthScopesPlug
  alias Pleroma.Web.OAuth.App

  require Logger

  plug(Pleroma.Web.ApiSpec.CastAndValidate)
  plug(:put_view, Pleroma.Web.MastodonAPI.AppView)

  plug(
    OAuthScopesPlug,
    %{scopes: ["write"], admin: true}
    when action in [:create, :index, :update, :delete]
  )

  action_fallback(Pleroma.Web.AdminAPI.FallbackController)

  defdelegate open_api_operation(action), to: Pleroma.Web.ApiSpec.Admin.OAuthAppOperation

  def index(conn, params) do
    search_params =
      params
      |> Map.take([:client_id, :page, :page_size, :trusted])
      |> Map.put(:client_name, params[:name])

    with {:ok, apps, count} <- App.search(search_params) do
      render(conn, "index.json",
        apps: apps,
        count: count,
        page_size: params.page_size,
        admin: true
      )
    end
  end

  def create(%{body_params: params} = conn, _) do
45
    params = Pleroma.Maps.put_if_present(params, :client_name, params[:name])
46
47
48
49
50
51
52
53
54
55
56

    case App.create(params) do
      {:ok, app} ->
        render(conn, "show.json", app: app, admin: true)

      {:error, changeset} ->
        json(conn, App.errors(changeset))
    end
  end

  def update(%{body_params: params} = conn, %{id: id}) do
57
    params = Pleroma.Maps.put_if_present(params, :client_name, params[:name])
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77

    with {:ok, app} <- App.update(id, params) do
      render(conn, "show.json", app: app, admin: true)
    else
      {:error, changeset} ->
        json(conn, App.errors(changeset))

      nil ->
        json_response(conn, :bad_request, "")
    end
  end

  def delete(conn, params) do
    with {:ok, _app} <- App.destroy(params.id) do
      json_response(conn, :no_content, "")
    else
      _ -> json_response(conn, :bad_request, "")
    end
  end
end