rbac system first stage

This commit is contained in:
2026-02-03 21:37:06 +11:00
parent 9f7e7c88a0
commit c4a4226647
38 changed files with 1966 additions and 114 deletions

View File

@@ -0,0 +1,56 @@
package handlers
import (
"context"
"git.haelnorr.com/h/oslstats/internal/db"
"git.haelnorr.com/h/oslstats/internal/rbac"
"git.haelnorr.com/h/oslstats/internal/roles"
"github.com/pkg/errors"
"github.com/uptrace/bun"
)
// shouldGrantAdmin checks if user's Discord ID is in admin list
func shouldGrantAdmin(user *db.User, cfg *rbac.Config) bool {
if cfg == nil || user == nil {
return false
}
if user.DiscordID == cfg.AdminDiscordID {
return true
}
return false
}
// ensureUserHasAdminRole grants admin role if not already granted
func ensureUserHasAdminRole(ctx context.Context, tx bun.Tx, user *db.User) error {
if user == nil {
return errors.New("user cannot be nil")
}
// Check if user already has admin role
hasAdmin, err := user.HasRole(ctx, tx, roles.Admin)
if err != nil {
return errors.Wrap(err, "user.HasRole")
}
if hasAdmin {
return nil // Already admin
}
// Get admin role
adminRole, err := db.GetRoleByName(ctx, tx, roles.Admin)
if err != nil {
return errors.Wrap(err, "db.GetRoleByName")
}
if adminRole == nil {
return errors.New("admin role not found in database")
}
// Grant admin role (nil grantedBy = system granted)
err = db.AssignRole(ctx, tx, user.ID, adminRole.ID, nil)
if err != nil {
return errors.Wrap(err, "db.AssignRole")
}
return nil
}