swagger configurado na rota chavenfe

This commit is contained in:
unknown
2025-03-29 15:06:21 -03:00
parent 5e4ef04b4a
commit 32bd7c14b3
29 changed files with 709 additions and 241 deletions

View File

@@ -10,7 +10,19 @@ import { UsersService } from '../users/users.service';
import { LoginDto } from '../auth/dto/login.dto';
import { ResultModel } from 'src/core/models/result.model';
import { ApiBody, ApiOkResponse, ApiUnauthorizedResponse } from '@nestjs/swagger';
import { ApiTags } from '@nestjs/swagger';
import { ApiResponse } from '@nestjs/swagger';
import { ApiOperation } from '@nestjs/swagger';
import { ApiBearerAuth } from '@nestjs/swagger';
import { ApiCreatedResponse } from '@nestjs/swagger';
import { ApiBadRequestResponse } from '@nestjs/swagger';
import { ApiNotFoundResponse } from '@nestjs/swagger';
import { ApiInternalServerErrorResponse } from '@nestjs/swagger';
import { ApiForbiddenResponse } from '@nestjs/swagger';
import { LoginResponseDto } from './dto/LoginResponseDto';
@ApiTags('Auth')
@Controller('api/v1/auth')
export class AuthController {
constructor(
@@ -19,24 +31,25 @@ export class AuthController {
) {}
@Post('login')
@ApiOperation({ summary: 'Realiza login e retorna um token JWT' })
@ApiBody({ type: LoginDto })
@ApiOkResponse({ description: 'Login realizado com sucesso' })
@ApiOkResponse({
description: 'Login realizado com sucesso',
type: LoginResponseDto,
})
@ApiUnauthorizedResponse({ description: 'Usuário ou senha inválidos' })
async login(@Body() model: LoginDto): Promise<any> {
async login(@Body() model: LoginDto): Promise<LoginResponseDto> {
const result = await this.usersService.authenticate({
userName: model.username,
password: model.password,
});
console.log('Resultado da autenticação:', result);
if (!result.success) {
throw new HttpException(
new ResultModel(false, result.error, null, result.error),
HttpStatus.UNAUTHORIZED,
);
}
if (!result.success) {
throw new HttpException(
new ResultModel(false, result.error, null, result.error),
HttpStatus.UNAUTHORIZED,
);
}
const user = result.data;
@@ -58,4 +71,4 @@ if (!result.success) {
token: token,
};
}
}
}

View File

@@ -1,26 +1,25 @@
/* eslint-disable @typescript-eslint/no-unused-vars */
import { Module } from '@nestjs/common';
import { AuthController } from './auth.controller';
import { AuthService } from './auth.service';
import { JwtModule, JwtService } from '@nestjs/jwt';
import { JwtModule } from '@nestjs/jwt';
import { PassportModule } from '@nestjs/passport';
import { UsersModule } from '../users/users.module';
import { AuthService } from './auth.service';
import { JwtStrategy } from '../strategies/jwt-strategy';
import { RedisModule } from 'src/core/configs/cache/redis.module';
import { UsersModule } from '../users/users.module';
import { AuthController } from './auth.controller';
@Module({
imports: [
UsersModule,
PassportModule.register({
defaultStrategy: 'jwt',
}),
JwtModule.register({
secret: '4557C0D7-DFB0-40DA-BF83-91A75103F7A9',
signOptions: {
expiresIn: 3600,
},
signOptions: { expiresIn: '8h' },
}),
PassportModule.register({ defaultStrategy: 'jwt' }),
RedisModule,
UsersModule,
],
controllers: [AuthController],
providers: [AuthService,JwtStrategy],
providers: [AuthService, JwtStrategy],
exports: [AuthService],
})
export class AuthModule {}

View File

@@ -4,6 +4,8 @@ import { Injectable } from '@nestjs/common';
import { JwtService, JwtSignOptions } from '@nestjs/jwt';
import { UsersService } from '../users/users.service';
import { JwtPayload } from '../models/jwt-payload.model';
import Redis from 'ioredis';

View File

@@ -1,82 +0,0 @@
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
exports.__esModule = true;
exports.AuthService = void 0;
/* eslint-disable prettier/prettier */
/* eslint-disable @typescript-eslint/no-unused-vars */
var common_1 = require("@nestjs/common");
var AuthService = /** @class */ (function () {
function AuthService(usersService, jwtService) {
this.usersService = usersService;
this.jwtService = jwtService;
}
AuthService.prototype.createToken = function (id, sellerId, username, email, storeId) {
return __awaiter(this, void 0, void 0, function () {
var user, options;
return __generator(this, function (_a) {
user = {
id: id,
sellerId: sellerId,
storeId: storeId,
username: username,
email: email
};
options = { expiresIn: '8h' };
return [2 /*return*/, this.jwtService.sign(user, options)];
});
});
};
AuthService.prototype.validateUser = function (payload) {
return __awaiter(this, void 0, Promise, function () {
return __generator(this, function (_a) {
return [2 /*return*/, payload];
});
});
};
AuthService = __decorate([
common_1.Injectable()
], AuthService);
return AuthService;
}());
exports.AuthService = AuthService;

View File

@@ -0,0 +1,12 @@
// login-response.dto.ts
import { ApiProperty } from '@nestjs/swagger';
export class LoginResponseDto {
@ApiProperty() id: number;
@ApiProperty() sellerId: number;
@ApiProperty() name: string;
@ApiProperty() username: string;
@ApiProperty() storeId: string;
@ApiProperty() email: string;
@ApiProperty() token: string;
}

View File

@@ -0,0 +1,118 @@
<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Documentação - Fluxo de Login</title>
<style>
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
background-color: #f9f9f9;
color: #333;
line-height: 1.6;
padding: 2rem;
}
h1, h2, h3 {
color: #007acc;
}
code, pre {
background-color: #eee;
padding: 1rem;
border-radius: 4px;
display: block;
white-space: pre-wrap;
margin-bottom: 1rem;
}
table {
width: 100%;
border-collapse: collapse;
margin: 1rem 0;
}
th, td {
border: 1px solid #ddd;
padding: 0.75rem;
}
th {
background-color: #007acc;
color: white;
}
.tag {
display: inline-block;
background: #007acc;
color: white;
padding: 0.2rem 0.6rem;
border-radius: 4px;
font-size: 0.85rem;
}
</style>
</head>
<body>
<h1>🔐 Fluxo de Login - Portal Juru API</h1>
<h2>📌 Rota de Login</h2>
<p><strong>URL:</strong> <code>POST /api/v1/auth/login</code></p>
<p><strong>Descrição:</strong> Autentica o usuário, valida regras de negócio e retorna um token JWT.</p>
<p><strong>Acesso:</strong> Público</p>
<h3>📤 Body (JSON)</h3>
<pre>{
"username": "joelson.r",
"password": "1010"
}</pre>
<h3>✅ Resposta (200 OK)</h3>
<pre>{
"id": 1498,
"sellerId": 2013,
"name": "JOELSON DE BRITO RIBEIRO",
"username": "JOELSON DE BRITO RIBEIRO",
"storeId": "4",
"email": "JOELSON.R@JURUNENSE.COM.BR",
"token": "eyJhbGciOiJIUzI1NiIsInR5..."
}</pre>
<h3>❌ Resposta (401 Unauthorized)</h3>
<pre>{
"success": false,
"message": "Usuário ou senha inválidos.",
"data": null,
"error": "Usuário ou senha inválidos."
}</pre>
<h2>🧱 Camadas e Responsabilidades</h2>
<table>
<tr><th>Camada</th><th>Responsabilidade</th></tr>
<tr><td>AuthController</td><td>Recebe requisição e coordena autenticação</td></tr>
<tr><td>UsersService</td><td>Orquestra os casos de uso (login, reset, troca senha)</td></tr>
<tr><td>AuthenticateUserService</td><td>Executa lógica de autenticação e validações</td></tr>
<tr><td>UserRepository</td><td>Executa SQL diretamente no Oracle</td></tr>
<tr><td>AuthService</td><td>Gera o token JWT com os dados do usuário</td></tr>
<tr><td>JwtStrategy</td><td>Valida o token em rotas protegidas, usando Redis como cache</td></tr>
<tr><td>RedisClientAdapter</td><td>Wrapper de acesso ao Redis com interface genérica e TTL</td></tr>
</table>
<h2>🧊 Redis na Autenticação</h2>
<ul>
<li><strong>Chave:</strong> <code>session:{userId}</code></li>
<li><strong>Valor:</strong> JSON serializado do usuário autenticado</li>
<li><strong>TTL:</strong> 8 horas</li>
<li><strong>Fallback:</strong> Se o cache não existir, consulta ao banco</li>
<li><strong>Auditoria:</strong> espaço reservado para log de acesso</li>
</ul>
<h2>🔐 Proteção de Rotas</h2>
<p>Rotas protegidas utilizam <code>@UseGuards(JwtAuthGuard)</code> e <code>@ApiBearerAuth()</code>.</p>
<p><strong>Header necessário:</strong></p>
<code>Authorization: Bearer &lt;token&gt;</code>
<h2>🚀 Melhorias Futuras</h2>
<ul>
<li>[ ] Blacklist de tokens para logout</li>
<li>[ ] Log de auditoria</li>
<li>[ ] Refresh Token</li>
<li>[ ] Controle de permissões/roles</li>
</ul>
<p><strong>Última atualização:</strong> 28/03/2025</p>
</body>
</html>

View File

@@ -1,24 +1,43 @@
/* eslint-disable @typescript-eslint/no-unused-vars */
import { Injectable, UnauthorizedException } from '@nestjs/common';
// ✅ jwt.strategy.ts
import { Inject, Injectable, UnauthorizedException } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { JwtPayload } from '../models/jwt-payload.model';
import { AuthService } from '../auth/auth.service';
import { UserRepository } from '../../auth/users/UserRepository';
import { RedisClientToken } from '../../core/configs/cache/redis-client.adapter.provider';
import { IRedisClient } from '../../core/configs/cache/IRedisClient';
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor(private readonly authService: AuthService) {
constructor(
@Inject(RedisClientToken) private readonly redis: IRedisClient,
private readonly userRepository: UserRepository,
) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: '4557C0D7-DFB0-40DA-BF83-91A75103F7A9',
secretOrKey: '4557C0D7-DFB0-40DA-BF83-91A75103F7A9',
});
}
async validate(payload: JwtPayload) {
const user = await this.authService.validateUser(payload);
if (!user) {
throw new UnauthorizedException();
const sessionKey = `session:${payload.id}`;
const user = await this.redis.get<any>(sessionKey);
if (user) {
// Audit log placeholder
// await this.auditAccess(user);
return user;
}
return user;
const userDb = await this.userRepository.findById(payload.id);
if (!userDb || userDb.situacao === 'I' || userDb.dataDesligamento) {
throw new UnauthorizedException('Usuário inválido ou inativo');
}
await this.redis.set(sessionKey, userDb, 60 * 60 * 8);
// Audit fallback
// await this.auditAccess(userDb, 'fallback');
return userDb;
}
}

View File

@@ -5,7 +5,7 @@ import { InjectDataSource } from '@nestjs/typeorm';
@Injectable()
export class UserRepository {
constructor(
@InjectDataSource('oracle') // especifica que queremos o DataSource da conexão 'oracle'
@InjectDataSource('oracle')
private readonly dataSource: DataSource,
) {}
@@ -61,4 +61,16 @@ export class UserRepository {
const result = await this.dataSource.query(sql, [sellerId, passwordHash]);
return result[0] || null;
}
async findById(id: number) {
const sql = `
SELECT MATRICULA AS "id", NOME AS "name", CODUSUR AS "sellerId",
CODFILIAL AS "storeId", EMAIL AS "email",
DTDEMISSAO as "dataDesligamento", SITUACAO as "situacao"
FROM PCEMPR
WHERE MATRICULA = :1
`;
const result = await this.dataSource.query(sql, [id]);
return result[0] || null;
}
}

View File

@@ -21,6 +21,6 @@ import { EmailService } from './email.service';
ChangePasswordService,
EmailService,
],
exports: [UsersService],
exports: [UsersService,UserRepository],
})
export class UsersModule {}