I'm a junior full-stack developer from Alexandria, Egypt, and this is another deep-dive from FaceMark, my face-recognition attendance system (a NestJS API + a Python AI service). This one is about authorization: how the API decides that a student can see their own attendance but can't touch anyone 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 whole system is three small pieces that fit together: a JWT guard that answers "who are you", a decorator that answers "who is allowed here", and a roles guard that compares the two.
Piece 1: The JWT guard (authentication)
// src/auth/guards/jwt-auth.guard.ts @Injectable() export class JwtAuthGuard extends AuthGuard('jwt') {} It's almost embarrassing how small this is. All it does is extend 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. That request.user is what the next piece relies on.
Piece 2: The @Roles decorator (declaring intent)
// src/auth/decorators/roles.decorator.ts export const ROLES_KEY = 'roles'; export const Roles = (...roles: Role[]) => SetMetadata(ROLES_KEY, roles); This doesn't do anything by itself. It just attaches metadata to a route: "this endpoint wants ADMIN and STAFF". I like this pattern because the rule lives exactly where the route is declared. You read the controller and you see the permission, instead of hunting through a config file somewhere else.
Piece 3: The roles guard (enforcing it)
// 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; } } A few decisions worth explaining:
-
getAllAndOverridewith handler first, class second. A route-level@Rolesbeats a controller-level one. That means I can set a sensible default on the whole controller and override it on the one endpoint that's different. - No metadata means public (within this guard). If a route has no
@Roles, this guard lets it through. Authentication is still enforced separately by the JWT guard, so "logged in but any role" is a deliberate state, not a loophole. - Fail with a useful message. The 403 tells you your role and what was required. When I was testing with tokens from different seed users, this saved me real debugging time.
How it looks 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 them left to right, so the JWT guard populates request.user before the roles guard reads it. Get the order wrong and the roles guard sees no user and rejects everything, which is 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 with the required roles spelled out. 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, and keeping them separate means either one can change without touching the other.
- Put the permission next to the route.
@Roles(Role.ADMIN, Role.STAFF)right above the handler is documentation that can't drift out of date the way a wiki page does. - Enums over strings. Every role reference goes through the
Roleenum, so a typo is a compile error, not a silently-never-matching string 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 deep-dives 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: ziad.taha3456@gmail.com
dev.to: https://dev.to/ziadtaha
