Keeping students out of staff endpoints: NestJS guards and roles in my attendance project
I'm a junior full-stack developer from Alexandria, Egypt. This is another post about FaceMark, my face-recognition attendance system (a NestJS API plus a Python AI service). This one covers authorization: how the API dec
I'm a junior full-stack developer from Alexandria, Egypt. This is another post about FaceMark, my face-recognition attendance system (a NestJS API plus a Python AI service). This one covers authorization: how the API decides that a student can see their own attendance but nobody else's, and that only staff and admins can pull class-wide records.
FaceMark has three roles, defined as a plain enum:
// src/common/enums/role.enum.ts
export enum Role {
ADMIN = 'admin',
STAFF = 'staff',
STUDENT = 'student',
}
The system is three small pieces: a JWT guard that answers "who are you", a decorator that answers "who is allowed here", and a roles guard that compares the two.
The JWT guard
// src/auth/guards/jwt-auth.guard.ts
@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {}
That's the whole file. It extends Passport's JWT AuthGuard: no valid token, no request. When the token is valid, the JWT strategy attaches the user (including their role) to the request object. The next piece reads request.user.
The @Roles decorator
// src/auth/decorators/roles.decorator.ts
export const ROLES_KEY = 'roles';
export const Roles = (...roles: Role[]) => SetMetadata(ROLES_KEY, roles);
This does nothing by itself. It attaches metadata to a route: "this endpoint wants ADMIN and STAFF". I like this pattern because the rule sits right where the route is declared. You read the controller and you see the permission, instead of hunting through a config file somewhere else.
The roles guard
// src/auth/guards/roles.guard.ts (trimmed)
@Injectable()
export class RolesGuard implements CanActivate {
constructor(private reflector: Reflector) {}
canActivate(context: ExecutionContext): boolean {
const requiredRoles = this.reflector.getAllAndOverride<Role[]>(ROLES_KEY, [
context.getHandler(),
context.getClass(),
]);
if (!requiredRoles) {
return true;
}
const { user } = context.switchToHttp().getRequest();
if (!user) {
throw new ForbiddenException('Access Denied: No authenticated user found in request.');
}
const hasRole = requiredRoles.some((role) => user.role === role);
if (!hasRole) {
throw new ForbiddenException(
`Access Denied: Your role '${user.role}' does not have permission to access this resource. Required roles: [${requiredRoles.join(', ')}]`
);
}
return true;
}
}
Three decisions in there:
getAllAndOverride checks the handler first, the class second. A route-level @Roles beats a controller-level one, so I can set a default on the whole controller and override it on the one endpoint that's different.
No metadata means the guard lets the request through. Authentication is still enforced by the JWT guard, so "logged in, any role" is a deliberate state, not a loophole.
The 403 message tells you your role and what was required. When I was testing with tokens from different seed users, this saved me real debugging time.
On a real controller
// src/attendance/controller/attendance.controller.ts (trimmed)
@UseGuards(JwtAuthGuard, RolesGuard)
@Controller('attendance')
export class AttendanceController {
@Get('my')
@Roles(Role.STUDENT)
async getMyAttendance(/* ... */) { /* student's own history */ }
@Get('course/:courseId')
@Roles(Role.ADMIN, Role.STAFF)
async getByCourse(/* ... */) { /* class-wide records */ }
@Get('track/:studentId')
@Roles(Role.ADMIN, Role.STAFF)
async trackStudent(/* ... */) { /* risk analysis for one student */ }
}
The order in @UseGuards(JwtAuthGuard, RolesGuard) matters. NestJS runs guards left to right, so the JWT guard fills request.user before the roles guard reads it. Get the order wrong and the roles guard sees no user and rejects everything. That was a confusing first bug to hit.
A student calling GET /attendance/my passes both guards and gets exactly their own records. The same student calling GET /attendance/course/3 gets a 403. Staff and admin pass both.
What I'd tell another junior dev
Authentication and authorization are separate questions. "Who are you" (JWT guard) and "are you allowed" (roles guard) live in different classes here, so either one can change without touching the other.
Put the permission next to the route. @Roles(Role.ADMIN, Role.STAFF) above the handler is documentation that can't drift out of date the way a wiki page does.
Use enums, not strings. Every role reference goes through the Role enum, so a typo is a compile error instead of a string that never matches at runtime.
Everything above is from the real repo, and you can read the full files there.
I'm a junior full-stack developer (Angular, NestJS, TypeScript, Python) in Alexandria, Egypt, open to junior roles and freelance work. More posts from this project:
- Circuit breaker + WAL engine: https://dev.to/ziadtaha/i-wrote-a-circuit-breaker-and-a-bitcask-style-wal-engine-for-my-face-recognition-api-with-real-1gcp
The NestJS-to-Python boundary: https://dev.to/ziadtaha/my-nestjs-api-talks-to-a-python-ai-microservice-heres-how-i-keep-the-boundary-honest-with-real-160g
GitHub: https://github.com/ZiadtahaM
Email: [email protected]
dev.to: https://dev.to/ziadtaha
Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes β full credit and traffic to the original publisher.