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(); 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; } }