refactor: use UUIDv7 and improve Role validations

- Change id from uuid_primary_key to uuid_v7_primary_key
- Replace custom validation with built-in one_of validation
- Add explicit on_delete: :restrict for users foreign key
- Update postgres references configuration
This commit is contained in:
Moritz 2026-01-06 18:14:16 +01:00
parent b569612a63
commit 82ec4e565a

View file

@ -42,6 +42,11 @@ defmodule Mv.Authorization.Role do
postgres do postgres do
table "roles" table "roles"
repo Mv.Repo repo Mv.Repo
references do
# Prevent deletion of roles that are assigned to users
reference :users, on_delete: :restrict
end
end end
code_interface do code_interface do
@ -75,27 +80,12 @@ defmodule Mv.Authorization.Role do
end end
validations do validations do
validate fn changeset, _context -> validate one_of(
permission_set_name = Ash.Changeset.get_attribute(changeset, :permission_set_name) :permission_set_name,
Mv.Authorization.PermissionSets.all_permission_sets()
if permission_set_name do |> Enum.map(&Atom.to_string/1)
valid_sets = ),
Mv.Authorization.PermissionSets.all_permission_sets() message: "must be one of: own_data, read_only, normal_user, admin"
|> Enum.map(&Atom.to_string/1)
if permission_set_name in valid_sets do
:ok
else
valid_sets_string = Enum.join(valid_sets, ", ")
{:error,
field: :permission_set_name,
message: "Invalid permission set name. Must be one of: #{valid_sets_string}"}
end
else
:ok
end
end
validate fn changeset, _context -> validate fn changeset, _context ->
if changeset.action_type == :destroy do if changeset.action_type == :destroy do
@ -114,7 +104,7 @@ defmodule Mv.Authorization.Role do
end end
attributes do attributes do
uuid_primary_key :id uuid_v7_primary_key :id
attribute :name, :string do attribute :name, :string do
allow_nil? false allow_nil? false