refactored for maintainability
This commit is contained in:
@@ -3,7 +3,6 @@ package rbac
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"git.haelnorr.com/h/golib/hws"
|
||||
"git.haelnorr.com/h/oslstats/internal/contexts"
|
||||
@@ -11,6 +10,7 @@ import (
|
||||
"git.haelnorr.com/h/oslstats/internal/permissions"
|
||||
"git.haelnorr.com/h/oslstats/internal/roles"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/uptrace/bun"
|
||||
)
|
||||
|
||||
// LoadPermissionsMiddleware loads user permissions into context after authentication
|
||||
@@ -26,46 +26,28 @@ func (c *Checker) LoadPermissionsMiddleware() hws.Middleware {
|
||||
return
|
||||
}
|
||||
|
||||
// Start transaction for loading permissions
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 15*time.Second)
|
||||
defer cancel()
|
||||
tx, err := c.conn.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
// Log but don't block - permission checks will fail gracefully
|
||||
var roles_ []*db.Role
|
||||
var perms []*db.Permission
|
||||
if err := db.WithTxFailSilently(r.Context(), c.conn, func(ctx context.Context, tx bun.Tx) error {
|
||||
var err error
|
||||
roles_, err = user.GetRoles(ctx, tx)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "user.GetRoles")
|
||||
}
|
||||
perms, err = user.GetPermissions(ctx, tx)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "user.GetPermissions")
|
||||
}
|
||||
return nil
|
||||
}); err != nil {
|
||||
c.s.LogError(hws.HWSError{
|
||||
Message: "Failed to start database transaction",
|
||||
Error: errors.Wrap(err, "c.conn.BeginTx"),
|
||||
Message: "Database error",
|
||||
Error: err,
|
||||
Level: hws.ErrorERROR,
|
||||
})
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
|
||||
// Load user's roles_ and permissions
|
||||
roles_, err := user.GetRoles(ctx, tx)
|
||||
if err != nil {
|
||||
c.s.LogError(hws.HWSError{
|
||||
Message: "Failed to get user roles",
|
||||
Error: errors.Wrap(err, "user.GetRoles"),
|
||||
Level: hws.ErrorERROR,
|
||||
})
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
|
||||
perms, err := user.GetPermissions(ctx, tx)
|
||||
if err != nil {
|
||||
c.s.LogError(hws.HWSError{
|
||||
Message: "Failed to get user permissions",
|
||||
Error: errors.Wrap(err, "user.GetPermissions"),
|
||||
Level: hws.ErrorERROR,
|
||||
})
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
|
||||
_ = tx.Commit() // read only transaction
|
||||
|
||||
// Build permission cache
|
||||
cache := &contexts.PermissionCache{
|
||||
@@ -88,7 +70,7 @@ func (c *Checker) LoadPermissionsMiddleware() hws.Middleware {
|
||||
}
|
||||
|
||||
// Add cache to context (type-safe)
|
||||
ctx = context.WithValue(ctx, contexts.PermissionCacheKey, cache)
|
||||
ctx := context.WithValue(r.Context(), contexts.PermissionCacheKey, cache)
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
})
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user