Fix WriteAccessGuard: use req.userRole from middleware (runs before guards)
The global WriteAccessGuard was checking req.user.role, but req.user is set by JwtAuthGuard (a per-controller guard) which runs AFTER global guards. TenantMiddleware sets req.userRole from the JWT before guards execute, so we now check that property first. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -13,9 +13,10 @@ export class WriteAccessGuard implements CanActivate {
|
|||||||
// Allow all read methods
|
// Allow all read methods
|
||||||
if (['GET', 'HEAD', 'OPTIONS'].includes(method)) return true;
|
if (['GET', 'HEAD', 'OPTIONS'].includes(method)) return true;
|
||||||
|
|
||||||
// If no user on request (unauthenticated endpoints like login/register), allow
|
// Determine role from either req.userRole (set by TenantMiddleware which runs
|
||||||
const user = request.user;
|
// before guards) or req.user.role (set by JwtAuthGuard Passport strategy).
|
||||||
if (!user) return true;
|
const role = request.userRole || request.user?.role;
|
||||||
|
if (!role) return true; // unauthenticated endpoints like login/register
|
||||||
|
|
||||||
// Check for @AllowViewer() exemption on handler or class
|
// Check for @AllowViewer() exemption on handler or class
|
||||||
const allowViewer = this.reflector.getAllAndOverride<boolean>(ALLOW_VIEWER_KEY, [
|
const allowViewer = this.reflector.getAllAndOverride<boolean>(ALLOW_VIEWER_KEY, [
|
||||||
@@ -25,7 +26,7 @@ export class WriteAccessGuard implements CanActivate {
|
|||||||
if (allowViewer) return true;
|
if (allowViewer) return true;
|
||||||
|
|
||||||
// Block viewer role from write operations
|
// Block viewer role from write operations
|
||||||
if (user.role === 'viewer') {
|
if (role === 'viewer') {
|
||||||
throw new ForbiddenException('Read-only users cannot modify data');
|
throw new ForbiddenException('Read-only users cannot modify data');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user