forked from Nova-reward/Nova-Rewards
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathadmin.guard.ts
More file actions
26 lines (20 loc) · 817 Bytes
/
Copy pathadmin.guard.ts
File metadata and controls
26 lines (20 loc) · 817 Bytes
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
import { Injectable, CanActivate, ExecutionContext, ForbiddenException } from '@nestjs/common';
import { Observable } from 'rxjs';
import { UserService } from '../../users/user.service';
@Injectable()
export class AdminGuard implements CanActivate {
constructor(private readonly userService: UserService) {}
async canActivate(context: ExecutionContext): Promise<boolean> {
const request = context.switchToHttp().getRequest();
const user = request.user;
if (!user) {
throw new ForbiddenException('User not authenticated');
}
// Get the full user from the database to check role
const dbUser = await this.userService.findById(user.userId);
if (dbUser.role !== 'admin') {
throw new ForbiddenException('Admin role required for this action');
}
return true;
}
}