mfa.guard.ts 961 B

123456789101112131415161718192021222324252627282930313233343536
  1. import {
  2. CanActivate,
  3. ExecutionContext,
  4. Injectable,
  5. UnauthorizedException,
  6. } from '@nestjs/common';
  7. import type { FastifyRequest } from 'fastify';
  8. import { User } from '@prisma/mysql/client';
  9. @Injectable()
  10. export class MfaGuard implements CanActivate {
  11. canActivate(context: ExecutionContext): boolean {
  12. const request = context
  13. .switchToHttp()
  14. .getRequest<FastifyRequest & { user?: User; mfaVerified?: boolean }>();
  15. const user = request.user;
  16. if (!user) {
  17. throw new UnauthorizedException('User not authenticated');
  18. }
  19. // Check if user has 2FA enabled
  20. const twoFAEnabled = !!(user.twoFA && String(user.twoFA).trim().length > 0);
  21. // If 2FA is enabled, verify it was completed
  22. if (twoFAEnabled && !request.mfaVerified) {
  23. throw new UnauthorizedException({
  24. statusCode: 401,
  25. message: 'MFA verification required',
  26. code: 'MFA_REQUIRED',
  27. });
  28. }
  29. return true;
  30. }
  31. }