Added AuthModule with services, controllers, and guards for authentication. Implements session management, role-based access control, 2FA, and DTOs for user login, registration, and token refresh.
29 lines
790 B
TypeScript
29 lines
790 B
TypeScript
import { CanActivate, ExecutionContext, Injectable } from "@nestjs/common";
|
|
import { Reflector } from "@nestjs/core";
|
|
import { RbacService } from "../rbac.service";
|
|
|
|
@Injectable()
|
|
export class RolesGuard implements CanActivate {
|
|
constructor(
|
|
private reflector: Reflector,
|
|
private rbacService: RbacService,
|
|
) {}
|
|
|
|
async canActivate(context: ExecutionContext): Promise<boolean> {
|
|
const requiredRoles = this.reflector.getAllAndOverride<string[]>("roles", [
|
|
context.getHandler(),
|
|
context.getClass(),
|
|
]);
|
|
if (!requiredRoles) {
|
|
return true;
|
|
}
|
|
const { user } = context.switchToHttp().getRequest();
|
|
if (!user) {
|
|
return false;
|
|
}
|
|
|
|
const userRoles = await this.rbacService.getUserRoles(user.sub);
|
|
return requiredRoles.some((role) => userRoles.includes(role));
|
|
}
|
|
}
|