- API auth uses current_user, not current_scope - Check membership role directly instead of using owner?/1 helper - Allow superusers to update organization settings - Fixes KeyError: key :current_scope not found Previous code assumed LiveView context with current_scope, but API requests only have current_user and current_organization_id assigned.
70 lines
2.3 KiB
Elixir
70 lines
2.3 KiB
Elixir
defmodule ToweropsWeb.Api.V1.OrganizationController do
|
|
@moduledoc "API controller for current organization settings."
|
|
use ToweropsWeb, :controller
|
|
|
|
import ToweropsWeb.Api.ErrorHelpers, only: [translate_errors: 1]
|
|
|
|
alias Towerops.Organizations
|
|
|
|
def show(conn, _params) do
|
|
organization_id = conn.assigns.current_organization_id
|
|
org = Organizations.get_organization!(organization_id)
|
|
json(conn, %{data: format_org(org)})
|
|
end
|
|
|
|
def update(conn, %{"organization" => attrs}) do
|
|
# Only organization owners can update organization settings
|
|
user = conn.assigns.current_user
|
|
organization_id = conn.assigns.current_organization_id
|
|
org = Organizations.get_organization!(organization_id)
|
|
|
|
# Check if user is owner (or superuser)
|
|
membership = Organizations.get_membership(org.id, user.id)
|
|
|
|
if user.is_superuser || (membership && membership.role == :owner) do
|
|
case Organizations.update_organization(org, attrs) do
|
|
{:ok, updated} ->
|
|
json(conn, %{data: format_org(updated)})
|
|
|
|
{:error, changeset} ->
|
|
conn
|
|
|> put_status(:unprocessable_entity)
|
|
|> json(%{errors: translate_errors(changeset)})
|
|
end
|
|
else
|
|
conn
|
|
|> put_status(:forbidden)
|
|
|> json(%{error: "Only organization owners can update organization settings"})
|
|
end
|
|
end
|
|
|
|
def update(conn, _params) do
|
|
conn |> put_status(:bad_request) |> json(%{error: "Missing 'organization' parameter"})
|
|
end
|
|
|
|
defp format_org(org) do
|
|
%{
|
|
id: org.id,
|
|
name: org.name,
|
|
slug: org.slug,
|
|
subscription_plan: org.subscription_plan,
|
|
use_sites: org.use_sites,
|
|
snmp_version: org.snmp_version,
|
|
snmp_community: org.snmp_community,
|
|
snmp_port: org.snmp_port,
|
|
snmp_transport: org.snmp_transport,
|
|
snmpv3_security_level: org.snmpv3_security_level,
|
|
snmpv3_username: org.snmpv3_username,
|
|
snmpv3_auth_protocol: org.snmpv3_auth_protocol,
|
|
snmpv3_priv_protocol: org.snmpv3_priv_protocol,
|
|
mikrotik_enabled: org.mikrotik_enabled,
|
|
mikrotik_username: org.mikrotik_username,
|
|
mikrotik_port: org.mikrotik_port,
|
|
mikrotik_ssh_port: org.mikrotik_ssh_port,
|
|
mikrotik_use_ssl: org.mikrotik_use_ssl,
|
|
default_agent_token_id: org.default_agent_token_id,
|
|
inserted_at: org.inserted_at,
|
|
updated_at: org.updated_at
|
|
}
|
|
end
|
|
end
|