| 123456789101112131415161718192021222324252627282930313233343536 |
- import {
- CanActivate,
- ExecutionContext,
- Injectable,
- UnauthorizedException,
- } from '@nestjs/common';
- import type { FastifyRequest } from 'fastify';
- import { User } from '@prisma/mysql/client';
- @Injectable()
- export class MfaGuard implements CanActivate {
- canActivate(context: ExecutionContext): boolean {
- const request = context
- .switchToHttp()
- .getRequest<FastifyRequest & { user?: User; mfaVerified?: boolean }>();
- const user = request.user;
- if (!user) {
- throw new UnauthorizedException('User not authenticated');
- }
- // Check if user has 2FA enabled
- const twoFAEnabled = !!(user.twoFA && String(user.twoFA).trim().length > 0);
- // If 2FA is enabled, verify it was completed
- if (twoFAEnabled && !request.mfaVerified) {
- throw new UnauthorizedException({
- statusCode: 401,
- message: 'MFA verification required',
- code: 'MFA_REQUIRED',
- });
- }
- return true;
- }
- }
|