1.8 KiB · text History 573fef1
defmodule VigilWeb.Api.V0.TeamController do
  @moduledoc """
  `GET /organizations/{org}/teams/` (`team:read` or `org:read`) and
  `POST /organizations/{org}/teams/` (`team:write`; `name`, optional
  `slug`; 201), in the shape of 2019 Sentry's `organization_teams.py`
  (BSD-3). Every team of the organization is listed, as in Sentry and
  GlitchTip; each lists only the projects the caller may see. Whoever
  makes a team joins it, as in Sentry.
  """
  use VigilWeb, :controller

  alias Vigil.{Organizations, Projects}
  alias VigilWeb.Api.Auth
  alias VigilWeb.Api.V0.{ProjectJSON, ReleaseController}

  def index(conn, %{"org" => org}) do
    with {:ok, conn} <- Auth.put_org(conn, org),
         {:ok, conn} <- Auth.require_any_scope(conn, ~w(team:read team:write team:admin org:read)) do
      scope = conn.assigns.current_scope
      visible = scope |> Projects.list_visible() |> Enum.map(& &1.id)

      json(
        conn,
        scope.organization
        |> Organizations.list_teams()
        |> Enum.map(&ProjectJSON.team(&1, scope, visible))
      )
    end
    |> ReleaseController.done()
  end

  def create(conn, %{"org" => org}) do
    with {:ok, conn} <- Auth.put_org(conn, org),
         {:ok, conn} <- Auth.require_scope(conn, "team:write") do
      scope = conn.assigns.current_scope

      case Organizations.create_team(scope, Map.take(conn.body_params, ~w(name slug))) do
        {:ok, team} ->
          # As Sentry: whoever makes a team is on it.
          :ok = Organizations.put_team_member(team.id, scope.member.id)
          team = Organizations.get_team_by_slug(scope.organization, team.slug)
          conn |> put_status(201) |> json(ProjectJSON.team(team, scope, []))

        {:error, reason} ->
          ReleaseController.error(conn, reason)
      end
    end
    |> ReleaseController.done()
  end
end