Concept Flow - Why guards control access
Request Received
Guard Checks Conditions
Allow
Controller Executes
When a request comes in, the guard checks if access is allowed. If yes, the controller runs. If no, access is denied.
canActivate(context: ExecutionContext): boolean {
const request = context.switchToHttp().getRequest();
return request.user?.isAdmin === true;
}| Step | Action | Input | Condition Checked | Result | Next Step |
|---|---|---|---|---|---|
| 1 | Receive request | { user: { isAdmin: true } } | N/A | N/A | Check guard |
| 2 | Guard reads user | { isAdmin: true } | user.isAdmin === true | True | Allow access |
| 3 | Controller runs | N/A | N/A | Request processed | Send response |
| 4 | Receive request | { user: { isAdmin: false } } | N/A | N/A | Check guard |
| 5 | Guard reads user | { isAdmin: false } | user.isAdmin === true | False | Deny access |
| 6 | Send error | N/A | N/A | 403 Forbidden | End |
| Variable | Start | After Step 2 | After Step 5 | Final |
|---|---|---|---|---|
| request.user.isAdmin | undefined | true | false | N/A |
| canActivate result | undefined | true | false | N/A |
Guards in NestJS check conditions before a controller runs. They return true to allow access or false to deny it. Guards control who can use routes. They help protect resources by blocking unauthorized requests. Use canActivate method to define guard logic.
canActivate(context: ExecutionContext) {
const request = context.switchToHttp().getRequest();
return request.user && request.user.isAdmin;
}isAdmin tries to access the guarded route?request.user exists and request.user.isAdmin is truthy.isAdminisAdmin is false or missing, the condition returns false, denying access.isAdmin is false or missing -> Option DcanActivate(context: ExecutionContext) {
const request = context.getRequest();
if (!request.user) {
throw new Error('User not found');
}
return true;
}context.getRequest() is invalid, the main issue is guard behavior on failure.request.user exists and request.user.role === 'admin' || request.user.role === 'moderator' uses OR (||) correctly. Return true if request.user exists and request.user.role === 'admin' && request.user.role === 'moderator' uses AND (&&) which is impossible for one role. Return true if request.user exists and request.user.role !== 'admin' || request.user.role !== 'moderator' uses negations incorrectly. Return true if request.user does not exist allows access without user.request.user exists and request.user.role === 'admin' || request.user.role === 'moderator' -> Option CPass the test and this pattern moves unknown