- packages/database: schema Prisma (users/sessions/roles/permissions/
user_roles/role_permissions/audit_logs/password_reset_tokens), migration
inicial e seed (permissoes+perfis+bootstrap super_admin com senha
aleatoria em FIRST_LOGIN.txt). Decisao de ORM (Prisma) documentada em
docs/ARCHITECTURE.md
- packages/shared: catalogo de permissoes (fonte unica usada por seed e API)
- apps/api: NestJS 11 + Fastify
- autenticacao: Argon2id, access JWT + refresh token opaco com rotacao,
cookies HttpOnly/SameSite=Lax, change/forgot/reset password
- rate limiting progressivo de login via Redis (bloqueio crescente por IP)
- RBAC reforcado no backend (PermissionsGuard), protecao contra
auto-elevacao de privilegio
- auditoria (audit_logs) nas acoes sensiveis, com redacao de segredos
- health checks reais (postgres+redis), swagger desabilitavel, logs
estruturados JSON com request_id de correlacao, filtro global de
excecoes sem vazar erro cru
- infrastructure/docker/api.Dockerfile: build multi-stage do monorepo pnpm
- docker-compose.yml: servico api na rede interna, sem porta publicada
Testado via containers reais: login, /me, refresh, change-password,
rate limit (7 tentativas -> 429), RBAC (nega/permite), bloqueio de
auto-elevacao (403), audit log populado, health checks, lint e testes
unitarios passando.
68 lines
1.9 KiB
TypeScript
68 lines
1.9 KiB
TypeScript
import {
|
|
CanActivate,
|
|
ExecutionContext,
|
|
Injectable,
|
|
UnauthorizedException,
|
|
} from '@nestjs/common';
|
|
import { Reflector } from '@nestjs/core';
|
|
import { JwtService } from '@nestjs/jwt';
|
|
import type { FastifyRequest } from 'fastify';
|
|
import { IS_PUBLIC_KEY } from '../decorators/public.decorator';
|
|
|
|
export interface AuthenticatedUser {
|
|
id: string;
|
|
email: string;
|
|
permissions: string[];
|
|
}
|
|
|
|
type RequestWithUser = FastifyRequest & { user?: AuthenticatedUser };
|
|
|
|
// Extrai o access token do cookie HttpOnly (fluxo normal do frontend) ou do
|
|
// header Authorization (útil para clients/scripts/testes).
|
|
function extractToken(request: FastifyRequest): string | null {
|
|
const cookieToken = request.cookies?.['access_token'];
|
|
if (cookieToken) return cookieToken;
|
|
|
|
const authHeader = request.headers.authorization;
|
|
if (authHeader?.startsWith('Bearer '))
|
|
return authHeader.slice('Bearer '.length);
|
|
|
|
return null;
|
|
}
|
|
|
|
@Injectable()
|
|
export class AuthGuard implements CanActivate {
|
|
constructor(
|
|
private readonly jwtService: JwtService,
|
|
private readonly reflector: Reflector,
|
|
) {}
|
|
|
|
async canActivate(context: ExecutionContext): Promise<boolean> {
|
|
const isPublic = this.reflector.getAllAndOverride<boolean>(IS_PUBLIC_KEY, [
|
|
context.getHandler(),
|
|
context.getClass(),
|
|
]);
|
|
if (isPublic) return true;
|
|
|
|
const request = context.switchToHttp().getRequest<RequestWithUser>();
|
|
const token = extractToken(request);
|
|
if (!token) throw new UnauthorizedException('Token de acesso ausente');
|
|
|
|
try {
|
|
const payload = await this.jwtService.verifyAsync<{
|
|
sub: string;
|
|
email: string;
|
|
permissions: string[];
|
|
}>(token);
|
|
request.user = {
|
|
id: payload.sub,
|
|
email: payload.email,
|
|
permissions: payload.permissions,
|
|
} satisfies AuthenticatedUser;
|
|
return true;
|
|
} catch {
|
|
throw new UnauthorizedException('Token de acesso inválido ou expirado');
|
|
}
|
|
}
|
|
}
|