feat: implementar melhorias na autenticação
- Adicionar refresh tokens para renovação automática de tokens - Implementar controle de sessões simultâneas - Adicionar blacklist de tokens para logout seguro - Implementar rate limiting para proteção contra ataques - Melhorar detecção de IP e identificação de sessão atual - Adicionar endpoints para gerenciamento de sessões - Corrigir inconsistências na validação de usuário - Atualizar configuração Redis com nova conexão
This commit is contained in:
49
src/auth/guards/rate-limiting.guard.ts
Normal file
49
src/auth/guards/rate-limiting.guard.ts
Normal file
@@ -0,0 +1,49 @@
|
||||
import { Injectable, CanActivate, ExecutionContext, HttpException, HttpStatus } from '@nestjs/common';
|
||||
import { RateLimitingService } from '../services/rate-limiting.service';
|
||||
|
||||
@Injectable()
|
||||
export class RateLimitingGuard implements CanActivate {
|
||||
constructor(private readonly rateLimitingService: RateLimitingService) {}
|
||||
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const request = context.switchToHttp().getRequest();
|
||||
const ip = this.getClientIp(request);
|
||||
|
||||
const isAllowed = await this.rateLimitingService.isAllowed(ip);
|
||||
|
||||
if (!isAllowed) {
|
||||
const attemptInfo = await this.rateLimitingService.getAttemptInfo(ip);
|
||||
|
||||
throw new HttpException(
|
||||
{
|
||||
success: false,
|
||||
error: 'Muitas tentativas de login. Tente novamente em alguns minutos.',
|
||||
data: null,
|
||||
details: {
|
||||
attempts: attemptInfo.attempts,
|
||||
remainingTime: attemptInfo.remainingTime,
|
||||
},
|
||||
},
|
||||
HttpStatus.TOO_MANY_REQUESTS,
|
||||
);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extrai o IP real do cliente considerando proxies
|
||||
* @param request Objeto de requisição
|
||||
* @returns Endereço IP do cliente
|
||||
*/
|
||||
private getClientIp(request: any): string {
|
||||
return (
|
||||
request.headers['x-forwarded-for']?.split(',')[0] ||
|
||||
request.headers['x-real-ip'] ||
|
||||
request.connection?.remoteAddress ||
|
||||
request.socket?.remoteAddress ||
|
||||
request.ip ||
|
||||
'127.0.0.1'
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user