big ole refactor
This commit is contained in:
@@ -3,6 +3,7 @@ package db
|
||||
import (
|
||||
"context"
|
||||
|
||||
"git.haelnorr.com/h/oslstats/internal/permissions"
|
||||
"git.haelnorr.com/h/oslstats/internal/roles"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/uptrace/bun"
|
||||
@@ -16,7 +17,7 @@ type UserRole struct {
|
||||
}
|
||||
|
||||
// AssignRole grants a role to a user
|
||||
func AssignRole(ctx context.Context, tx bun.Tx, userID, roleID int) error {
|
||||
func AssignRole(ctx context.Context, tx bun.Tx, userID, roleID int, audit *AuditMeta) error {
|
||||
if userID <= 0 {
|
||||
return errors.New("userID must be positive")
|
||||
}
|
||||
@@ -28,8 +29,20 @@ func AssignRole(ctx context.Context, tx bun.Tx, userID, roleID int) error {
|
||||
UserID: userID,
|
||||
RoleID: roleID,
|
||||
}
|
||||
details := map[string]any{
|
||||
"action": "grant",
|
||||
"role_id": roleID,
|
||||
}
|
||||
info := &AuditInfo{
|
||||
string(permissions.UsersManageRoles),
|
||||
"user",
|
||||
userID,
|
||||
details,
|
||||
}
|
||||
err := Insert(tx, userRole).
|
||||
ConflictNothing("user_id", "role_id").Exec(ctx)
|
||||
ConflictNothing("user_id", "role_id").
|
||||
WithAudit(audit, info).
|
||||
Exec(ctx)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "db.Insert")
|
||||
}
|
||||
@@ -38,7 +51,7 @@ func AssignRole(ctx context.Context, tx bun.Tx, userID, roleID int) error {
|
||||
}
|
||||
|
||||
// RevokeRole removes a role from a user
|
||||
func RevokeRole(ctx context.Context, tx bun.Tx, userID, roleID int) error {
|
||||
func RevokeRole(ctx context.Context, tx bun.Tx, userID, roleID int, audit *AuditMeta) error {
|
||||
if userID <= 0 {
|
||||
return errors.New("userID must be positive")
|
||||
}
|
||||
@@ -46,9 +59,20 @@ func RevokeRole(ctx context.Context, tx bun.Tx, userID, roleID int) error {
|
||||
return errors.New("roleID must be positive")
|
||||
}
|
||||
|
||||
details := map[string]any{
|
||||
"action": "revoke",
|
||||
"role_id": roleID,
|
||||
}
|
||||
info := &AuditInfo{
|
||||
string(permissions.UsersManageRoles),
|
||||
"user",
|
||||
userID,
|
||||
details,
|
||||
}
|
||||
err := DeleteItem[UserRole](tx).
|
||||
Where("user_id = ?", userID).
|
||||
Where("role_id = ?", roleID).
|
||||
WithAudit(audit, info).
|
||||
Delete(ctx)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "DeleteItem")
|
||||
|
||||
Reference in New Issue
Block a user