All files / src/controllers sms-improved.controller.ts

0% Statements 0/55
0% Branches 0/18
0% Functions 0/2
0% Lines 0/55

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183                                                                                                                                                                                                                                                                                                                                                                             
import { Request, Response } from 'express';
import { SmsService } from '../services/sms';
import { verificationCodes } from '../utils/verification-codes';
import { SessionManager } from '../utils/session-manager';
import { Validator } from '../utils/validation';
import { Logger } from '../utils/logger';
import { 
  RateLimitError, 
  BusinessRuleError, 
  ExternalServiceError,
  AppError,
  ErrorCode 
} from '../types/errors';
import { asyncHandler } from '../middleware/error-handler';
 
export class SmsImprovedController {
  static sendCode = asyncHandler(async (req: Request, res: Response): Promise<void> => {
    const requestId = req.headers['x-request-id'] as string;
    const { phoneNumber } = req.body;
 
    // Validate input
    Validator.validate(req.body, Validator.phoneRules(), requestId);
 
    Logger.info('SMS code request initiated', {
      requestId,
      phoneNumber: phoneNumber.replace(/\d(?=\d{4})/g, '*') // Mask phone number
    });
 
    // Check rate limiting
    const existingVerification = verificationCodes.get(phoneNumber);
    if (existingVerification) {
      const timeSinceLastSend = Date.now() - existingVerification.timestamp;
      if (timeSinceLastSend < 30000) { // 30 seconds
        throw new RateLimitError(
          'Veuillez attendre 30 secondes avant de demander un nouveau code',
          requestId
        );
      }
    }
 
    // Generate and store code
    const code = SmsService.generateCode();
    verificationCodes.set(phoneNumber, {
      code,
      timestamp: Date.now(),
      attempts: 0
    });
 
    // Send SMS
    const message = `Votre code de vérification LeCoffre est : ${code}`;
    const result = await SmsService.sendSms(phoneNumber, message);
 
    if (!result.success) {
      Logger.error('SMS sending failed', {
        requestId,
        phoneNumber: phoneNumber.replace(/\d(?=\d{4})/g, '*'),
        error: result.error
      });
 
      throw new ExternalServiceError('SMS', result.error || 'Échec de l\'envoi du SMS');
    }
 
    Logger.info('SMS code sent successfully', {
      requestId,
      phoneNumber: phoneNumber.replace(/\d(?=\d{4})/g, '*')
    });
 
    res.json({
      success: true,
      message: 'Code envoyé avec succès'
    });
  });
 
  static verifyCode = asyncHandler(async (req: Request, res: Response): Promise<void> => {
    const requestId = req.headers['x-request-id'] as string;
    const { phoneNumber, code } = req.body;
 
    // Validate input
    Validator.validate(req.body, [
      ...Validator.phoneRules(),
      {
        field: 'code',
        required: true,
        type: 'string',
        minLength: 4,
        maxLength: 6
      }
    ], requestId);
 
    Logger.info('SMS code verification initiated', {
      requestId,
      phoneNumber: phoneNumber.replace(/\d(?=\d{4})/g, '*')
    });
 
    // Development shortcut
    if (code === '1234') {
      const sessionId = SessionManager.createSession(phoneNumber);
      
      Logger.info('Development code used', {
        requestId,
        phoneNumber: phoneNumber.replace(/\d(?=\d{4})/g, '*'),
        sessionId
      });
 
      res.json({
        success: true,
        message: 'Code vérifié avec succès',
        sessionId: sessionId
      });
      return;
    }
 
    const verification = verificationCodes.get(phoneNumber);
 
    if (!verification) {
      throw new BusinessRuleError(
        'Aucun code n\'a été envoyé à ce numéro',
        undefined,
        requestId
      );
    }
 
    // Check expiration (5 minutes)
    if (Date.now() - verification.timestamp > 5 * 60 * 1000) {
      verificationCodes.delete(phoneNumber);
      throw new BusinessRuleError(
        'Le code a expiré',
        undefined,
        requestId
      );
    }
 
    // Verify code
    if (verification.code.toString() === code.toString()) {
      verificationCodes.delete(phoneNumber);
      
      const sessionId = SessionManager.createSession(phoneNumber);
      
      Logger.info('SMS code verified successfully', {
        requestId,
        phoneNumber: phoneNumber.replace(/\d(?=\d{4})/g, '*'),
        sessionId
      });
      
      res.json({
        success: true,
        message: 'Code vérifié avec succès',
        sessionId: sessionId
      });
    } else {
      verification.attempts += 1;
 
      if (verification.attempts >= 3) {
        verificationCodes.delete(phoneNumber);
        
        Logger.warn('Too many SMS verification attempts', {
          requestId,
          phoneNumber: phoneNumber.replace(/\d(?=\d{4})/g, '*'),
          attempts: verification.attempts
        });
 
        throw new BusinessRuleError(
          'Trop de tentatives. Veuillez demander un nouveau code',
          undefined,
          requestId
        );
      } else {
        Logger.warn('Invalid SMS code provided', {
          requestId,
          phoneNumber: phoneNumber.replace(/\d(?=\d{4})/g, '*'),
          attempts: verification.attempts
        });
 
        throw new BusinessRuleError(
          'Code incorrect',
          [{ field: 'code', value: code, constraints: ['Code de vérification incorrect'] }],
          requestId
        );
      }
    }
  });
}