Update seeds to create all 5 authorization roles

This commit is contained in:
Moritz 2026-01-24 19:13:13 +01:00
parent 0dbbc96353
commit 9557d8ae6b
Signed by: moritz
GPG key ID: 1020A035E5DD0824

View file

@ -129,28 +129,76 @@ end
# Get admin email from environment variable or use default
admin_email = System.get_env("ADMIN_EMAIL") || "admin@localhost"
# Create admin role (used for assigning to admin users)
admin_role =
case Authorization.list_roles() do
{:ok, roles} ->
case Enum.find(roles, &(&1.name == "Admin" && &1.permission_set_name == "admin")) do
nil ->
# Create admin role if it doesn't exist
case Authorization.create_role(%{
# Create all authorization roles (idempotent - creates only if they don't exist)
# Roles are created using create_role_with_system_flag to allow setting is_system_role
role_configs = [
%{
name: "Mitglied",
description: "Default member role with access to own data only",
permission_set_name: "own_data",
is_system_role: true
},
%{
name: "Vorstand",
description: "Board member with read access to all member data",
permission_set_name: "read_only",
is_system_role: false
},
%{
name: "Kassenwart",
description: "Treasurer with full member and payment management",
permission_set_name: "normal_user",
is_system_role: false
},
%{
name: "Buchhaltung",
description: "Accounting with read-only access for auditing",
permission_set_name: "read_only",
is_system_role: false
},
%{
name: "Admin",
description: "Administrator with full access",
permission_set_name: "admin"
}) do
{:ok, role} -> role
{:error, _error} -> nil
description: "Administrator with unrestricted access",
permission_set_name: "admin",
is_system_role: false
}
]
# Create or update each role
Enum.each(role_configs, fn role_data ->
case Mv.Authorization.Role
|> Ash.Query.filter(name == ^role_data.name)
|> Ash.read_one(authorize?: false, domain: Mv.Authorization) do
{:ok, existing_role} when not is_nil(existing_role) ->
# Role exists - update if needed (preserve is_system_role)
if existing_role.permission_set_name != role_data.permission_set_name or
existing_role.description != role_data.description do
existing_role
|> Ash.Changeset.for_update(:update_role, %{
description: role_data.description,
permission_set_name: role_data.permission_set_name
})
|> Ash.update!(authorize?: false, domain: Mv.Authorization)
end
role ->
role
end
{:ok, nil} ->
# Role doesn't exist - create it
Mv.Authorization.Role
|> Ash.Changeset.for_create(:create_role_with_system_flag, role_data)
|> Ash.create!(authorize?: false, domain: Mv.Authorization)
{:error, _error} ->
nil
{:error, error} ->
IO.puts("Warning: Failed to check for role #{role_data.name}: #{inspect(error)}")
end
end)
# Get admin role for assignment to admin user
admin_role =
case Mv.Authorization.Role
|> Ash.Query.filter(name == "Admin")
|> Ash.read_one(authorize?: false, domain: Mv.Authorization) do
{:ok, role} when not is_nil(role) -> role
_ -> nil
end
if is_nil(admin_role) do