30 lines
1.1 KiB
TypeScript
30 lines
1.1 KiB
TypeScript
import { Injectable, CanActivate, ExecutionContext, ForbiddenException } from '@nestjs/common';
|
|
import { PrismaService } from './prisma.service';
|
|
|
|
@Injectable()
|
|
export class AdminGuard implements CanActivate {
|
|
constructor(private prisma: PrismaService) {}
|
|
|
|
async canActivate(context: ExecutionContext): Promise<boolean> {
|
|
const request = context.switchToHttp().getRequest();
|
|
|
|
// Lưu ý: request.user thường được đính kèm bởi một AuthGuard (JWT/Passport) chạy trước đó.
|
|
const user = request.user;
|
|
|
|
if (!user || !user.id) {
|
|
throw new ForbiddenException('Yêu cầu xác thực không hợp lệ. Vui lòng đăng nhập.');
|
|
}
|
|
|
|
// Kiểm tra trực tiếp từ database để đảm bảo quyền isAdmin là chính xác nhất cho các tác vụ nhạy cảm
|
|
const dbUser = await this.prisma.user.findUnique({
|
|
where: { id: user.id },
|
|
select: { isAdmin: true },
|
|
});
|
|
|
|
if (!dbUser || !dbUser.isAdmin) {
|
|
throw new ForbiddenException('Truy cập bị từ chối. Bạn không có quyền quản trị viên hệ thống.');
|
|
}
|
|
|
|
return true;
|
|
}
|
|
} |