All files / src/features/auth/guards roles.guard.ts

100% Statements 10/10
100% Branches 4/4
100% Functions 3/3
100% Lines 8/8

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29              62x     5x       5x 1x   4x 4x       4x     4x      
import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common'
import { Reflector } from '@nestjs/core'
import { ROLES_KEY } from '../decorators/roles.decorator'
import { AuthUser } from '../providers/auth-provider.interface'
 
@Injectable()
export class RolesGuard implements CanActivate {
    constructor(private reflector: Reflector) {}
 
    canActivate(context: ExecutionContext): boolean {
        const requiredRoles = this.reflector.getAllAndOverride<string[]>(ROLES_KEY, [
            context.getHandler(),
            context.getClass(),
        ])
        if (!requiredRoles) {
            return true
        }
        const request = context.switchToHttp().getRequest<{ user: AuthUser }>()
        const user = request.user
 
        // If no user (not authenticated yet), AuthGuard should have failed before,
        // but good to check.
        if (!user) return false
 
        // Check if user has one of the required roles
        return requiredRoles.some((role) => user.role === role)
    }
}