feat: check role assignment

This commit is contained in:
2025-06-30 00:08:14 +02:00
parent f5c61bb6a0
commit 0c24ed9382
3 changed files with 32 additions and 4 deletions

View File

@ -41,7 +41,7 @@ VALUES (
SELECT id
FROM permissions p
WHERE p.scope = split_part($2, '_', 1)
AND p.name = substring($2 FROM position('_' IN $2) + 1)
AND p.name = right($2, length($2) - position('_' IN $2))
)
)
`
@ -103,6 +103,24 @@ func (q *Queries) FindRole(ctx context.Context, arg FindRoleParams) (Role, error
return i, err
}
const getRoleAssignment = `-- name: GetRoleAssignment :one
SELECT role_id, permission_id FROM role_permissions
WHERE role_id = $1 AND permission_id = (SELECT id FROM permissions p WHERE p.scope = split_part($2, '_', 1) AND p.name = right($2, length($2) - position('_' IN $2)))
LIMIT 1
`
type GetRoleAssignmentParams struct {
RoleID uuid.UUID `json:"role_id"`
Key string `json:"key"`
}
func (q *Queries) GetRoleAssignment(ctx context.Context, arg GetRoleAssignmentParams) (RolePermission, error) {
row := q.db.QueryRow(ctx, getRoleAssignment, arg.RoleID, arg.Key)
var i RolePermission
err := row.Scan(&i.RoleID, &i.PermissionID)
return i, err
}
const getRolesGroupedWithPermissions = `-- name: GetRolesGroupedWithPermissions :many
SELECT
r.scope,

View File

@ -199,11 +199,16 @@ func EnsureSystemPermissions(ctx context.Context, repo *repository.Queries) {
}
for _, perm := range role.Permissions {
if err := repo.AssignRolePermission(ctx, repository.AssignRolePermissionParams{
if _, exists := repo.GetRoleAssignment(ctx, repository.GetRoleAssignmentParams{
RoleID: found.ID,
Key: perm,
}); err != nil {
log.Fatalf("ERR: Failed to assign permission '%s' to SYSTEM role %s: %v\n", perm, found.Name, err)
}); exists != nil {
if err := repo.AssignRolePermission(ctx, repository.AssignRolePermissionParams{
RoleID: found.ID,
Key: perm,
}); err != nil {
log.Fatalf("ERR: Failed to assign permission '%s' to SYSTEM role %s: %v\n", perm, found.Name, err)
}
}
}
}

View File

@ -53,6 +53,11 @@ INSERT INTO roles (name, scope, description)
VALUES ($1, $2, $3)
RETURNING *;
-- name: GetRoleAssignment :one
SELECT * FROM role_permissions
WHERE role_id = $1 AND permission_id = (SELECT id FROM permissions p WHERE p.scope = split_part(sqlc.arg('key'), '_', 1) AND p.name = right(sqlc.arg('key'), length(sqlc.arg('key')) - position('_' IN sqlc.arg('key'))))
LIMIT 1;
-- name: AssignRolePermission :exec
INSERT INTO role_permissions (role_id, permission_id)
VALUES (