more refactors

This commit is contained in:
2026-02-08 19:57:12 +11:00
parent 1a2bdaf4cf
commit 97342e08fe
17 changed files with 334 additions and 308 deletions

View File

@@ -33,70 +33,28 @@ type RolePermission struct {
Permission *Permission `bun:"rel:belongs-to,join:permission_id=id"`
}
func (r Role) isSystem() bool {
return r.IsSystem
}
// GetRoleByName queries the database for a role matching the given name
// Returns nil, nil if no role is found
func GetRoleByName(ctx context.Context, tx bun.Tx, name roles.Role) (*Role, error) {
if name == "" {
return nil, errors.New("name cannot be empty")
}
role := new(Role)
err := tx.NewSelect().
Model(role).
Where("name = ?", name).
Limit(1).
Scan(ctx)
if err != nil {
if err == sql.ErrNoRows {
return nil, nil
}
return nil, errors.Wrap(err, "tx.NewSelect")
}
return role, nil
return GetByField[Role](tx, "name", name).GetFirst(ctx)
}
// GetRoleByID queries the database for a role matching the given ID
// Returns nil, nil if no role is found
func GetRoleByID(ctx context.Context, tx bun.Tx, id int) (*Role, error) {
if id <= 0 {
return nil, errors.New("id must be positive")
}
role := new(Role)
err := tx.NewSelect().
Model(role).
Where("id = ?", id).
Limit(1).
Scan(ctx)
if err != nil {
if err == sql.ErrNoRows {
return nil, nil
}
return nil, errors.Wrap(err, "tx.NewSelect")
}
return role, nil
return GetByID[Role](tx, id).GetFirst(ctx)
}
// GetRoleWithPermissions loads a role and all its permissions
func GetRoleWithPermissions(ctx context.Context, tx bun.Tx, id int) (*Role, error) {
if id <= 0 {
return nil, errors.New("id must be positive")
}
role := new(Role)
err := tx.NewSelect().
Model(role).
Where("id = ?", id).
Relation("Permissions").
Limit(1).
Scan(ctx)
if err != nil {
if err == sql.ErrNoRows {
return nil, nil
}
return nil, errors.Wrap(err, "tx.NewSelect")
}
return role, nil
return GetByID[Role](tx, id).Relation("Permissions").GetFirst(ctx)
}
// ListAllRoles returns all roles
@@ -155,28 +113,7 @@ func DeleteRole(ctx context.Context, tx bun.Tx, id int) error {
if id <= 0 {
return errors.New("id must be positive")
}
// Check if role is system role
role, err := GetRoleByID(ctx, tx, id)
if err != nil {
return errors.Wrap(err, "GetRoleByID")
}
if role == nil {
return errors.New("role not found")
}
if role.IsSystem {
return errors.New("cannot delete system role")
}
_, err = tx.NewDelete().
Model((*Role)(nil)).
Where("id = ?", id).
Exec(ctx)
if err != nil {
return errors.Wrap(err, "tx.NewDelete")
}
return nil
return DeleteWithProtection[Role](ctx, tx, id)
}
// AddPermissionToRole grants a permission to a role