proteje rotas com JwtAuthGuard e documenta endpoints com Swagger
This commit is contained in:
@@ -1,5 +1,3 @@
|
||||
/* eslint-disable prettier/prettier */
|
||||
/* eslint-disable @typescript-eslint/no-unused-vars */
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
@@ -9,37 +7,47 @@ import {
|
||||
} from '@nestjs/common';
|
||||
import { AuthService } from './auth.service';
|
||||
import { UsersService } from '../users/users.service';
|
||||
import { LoginDto } from '../auth/dto/login.dto';
|
||||
import { ResultModel } from 'src/core/models/result.model';
|
||||
import { LoginDto } from '../dto/login.dto';
|
||||
import { ApiBody, ApiOkResponse, ApiUnauthorizedResponse } from '@nestjs/swagger';
|
||||
|
||||
@Controller('api/v1/auth')
|
||||
export class AuthController {
|
||||
constructor(
|
||||
private usersService: UsersService,
|
||||
private authService: AuthService,
|
||||
) { }
|
||||
private readonly usersService: UsersService,
|
||||
private readonly authService: AuthService,
|
||||
) {}
|
||||
|
||||
@Post('login')
|
||||
async login(@Body() model: LoginDto): Promise<any> {
|
||||
const user = await this.usersService.authenticate({
|
||||
userName: model.username,
|
||||
password: model.password,
|
||||
});
|
||||
|
||||
if (!user)
|
||||
throw new HttpException(
|
||||
new ResultModel(false, 'Usuário ou senha inválidos.', null, null),
|
||||
HttpStatus.UNAUTHORIZED,
|
||||
);
|
||||
|
||||
@ApiBody({ type: LoginDto })
|
||||
@ApiOkResponse({ description: 'Login realizado com sucesso' })
|
||||
@ApiUnauthorizedResponse({ description: 'Usuário ou senha inválidos' })
|
||||
async login(@Body() model: LoginDto): Promise<any> {
|
||||
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,
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
const user = result.data;
|
||||
|
||||
const token = await this.authService.createToken(
|
||||
user.id,
|
||||
user.sellerId,
|
||||
user.name,
|
||||
user.name,
|
||||
user.email,
|
||||
user.storeId
|
||||
user.storeId,
|
||||
);
|
||||
|
||||
|
||||
return {
|
||||
id: user.id,
|
||||
sellerId: user.sellerId,
|
||||
@@ -50,4 +58,4 @@ async login(@Body() model: LoginDto): Promise<any> {
|
||||
token: token,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,7 +5,7 @@ import { AuthService } from './auth.service';
|
||||
import { JwtModule, JwtService } from '@nestjs/jwt';
|
||||
import { PassportModule } from '@nestjs/passport';
|
||||
import { UsersModule } from '../users/users.module';
|
||||
|
||||
import { JwtStrategy } from '../strategies/jwt-strategy';
|
||||
@Module({
|
||||
imports: [
|
||||
UsersModule,
|
||||
@@ -20,7 +20,7 @@ import { UsersModule } from '../users/users.module';
|
||||
}),
|
||||
],
|
||||
controllers: [AuthController],
|
||||
providers: [AuthService],
|
||||
providers: [AuthService,JwtStrategy],
|
||||
exports: [AuthService],
|
||||
})
|
||||
export class AuthModule {}
|
||||
|
||||
@@ -6,6 +6,7 @@ import { UsersService } from '../users/users.service';
|
||||
import { JwtPayload } from '../models/jwt-payload.model';
|
||||
|
||||
|
||||
|
||||
@Injectable()
|
||||
export class AuthService {
|
||||
constructor(
|
||||
@@ -25,8 +26,7 @@ export class AuthService {
|
||||
return this.jwtService.sign(user, options);
|
||||
}
|
||||
|
||||
async validateUser(payload: JwtPayload): Promise<any> {
|
||||
//return await this.accountService.findOneByUsername(payload.username);
|
||||
async validateUser(payload: JwtPayload): Promise<JwtPayload | null> {
|
||||
return payload;
|
||||
}
|
||||
}
|
||||
7
src/auth/auth/authenticate-user.command.ts
Normal file
7
src/auth/auth/authenticate-user.command.ts
Normal file
@@ -0,0 +1,7 @@
|
||||
export class AuthenticateUserCommand {
|
||||
constructor(
|
||||
public readonly username: string,
|
||||
public readonly password: string,
|
||||
) {}
|
||||
}
|
||||
|
||||
@@ -1,23 +1,29 @@
|
||||
import { Injectable, ForbiddenException } from '@nestjs/common';
|
||||
import { UserRepository } from '../users/UserRepository';
|
||||
import { AuthenticateUserCommand } from './authenticate-user.command';
|
||||
import { Result } from '../models/result';
|
||||
|
||||
@Injectable()
|
||||
export class AuthenticateUserService {
|
||||
constructor(private readonly userRepository: UserRepository) {}
|
||||
|
||||
async execute(username: string, password: string) {
|
||||
async execute(command: AuthenticateUserCommand): Promise<Result<any>> {
|
||||
const { username, password } = command;
|
||||
|
||||
const user = await this.userRepository.findByUsernameAndPassword(username, password);
|
||||
|
||||
if (!user) return null;
|
||||
if (!user) {
|
||||
return Result.fail('Usuário ou senha inválidos');
|
||||
}
|
||||
|
||||
if (user.dataDesligamento !== null) {
|
||||
throw new ForbiddenException('Usuário desligado da empresa, login não permitido!');
|
||||
return Result.fail('Usuário desligado da empresa, login não permitido!');
|
||||
}
|
||||
|
||||
if (user.situacao === 'I') {
|
||||
throw new ForbiddenException('Usuário inativo, login não permitido!');
|
||||
return Result.fail('Usuário inativo, login não permitido!');
|
||||
}
|
||||
|
||||
return user;
|
||||
return Result.ok(user);
|
||||
}
|
||||
}
|
||||
|
||||
82
src/auth/auth/dist/auth.service.js
vendored
Normal file
82
src/auth/auth/dist/auth.service.js
vendored
Normal file
@@ -0,0 +1,82 @@
|
||||
"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;
|
||||
11
src/auth/auth/dto/login.dto.ts
Normal file
11
src/auth/auth/dto/login.dto.ts
Normal file
@@ -0,0 +1,11 @@
|
||||
import { IsString, IsNotEmpty } from 'class-validator';
|
||||
|
||||
export class LoginDto {
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
username: string;
|
||||
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
password: string;
|
||||
}
|
||||
46
src/auth/doc/doc.txt
Normal file
46
src/auth/doc/doc.txt
Normal file
@@ -0,0 +1,46 @@
|
||||
Controller
|
||||
↓ recebe LoginDto
|
||||
UsersService
|
||||
↓ monta o AuthenticateUserCommand
|
||||
AuthenticateUserService
|
||||
↓ executa regras de negócio
|
||||
UserRepository
|
||||
↓ executa query no banco
|
||||
Result<User>
|
||||
← resposta encapsulada
|
||||
|
||||
|
||||
1. LoginController
|
||||
Entrada da requisição HTTP (POST /auth/login)
|
||||
|
||||
Recebe LoginDto com email e password
|
||||
|
||||
Encaminha para o UsersService
|
||||
|
||||
2. UsersService
|
||||
Cria e valida o comando AuthenticateUserCommand
|
||||
|
||||
Chama o serviço de autenticação de domínio (AuthenticateUserService)
|
||||
|
||||
3. AuthenticateUserService
|
||||
Lógica de negócio da autenticação:
|
||||
|
||||
Busca usuário pelo e-mail
|
||||
|
||||
Verifica se o usuário está ativo
|
||||
|
||||
Valida a senha com hash
|
||||
|
||||
Retorna Result<User>
|
||||
|
||||
4. UserRepository
|
||||
Camada de persistência (interface com o banco de dados)
|
||||
|
||||
Executa a query findByEmail(email: string)
|
||||
|
||||
5. Result<T>
|
||||
Objeto genérico de retorno que encapsula:
|
||||
|
||||
Sucesso (success = true, com data: User)
|
||||
|
||||
Falha (success = false, com error: string)
|
||||
@@ -1,5 +0,0 @@
|
||||
export class LoginDto {
|
||||
username: string;
|
||||
password: string;
|
||||
}
|
||||
|
||||
5
src/auth/guards/jwt-auth.guard.ts
Normal file
5
src/auth/guards/jwt-auth.guard.ts
Normal file
@@ -0,0 +1,5 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { AuthGuard } from '@nestjs/passport';
|
||||
|
||||
@Injectable()
|
||||
export class JwtAuthGuard extends AuthGuard('jwt') {}
|
||||
@@ -10,7 +10,7 @@ export class JwtStrategy extends PassportStrategy(Strategy) {
|
||||
constructor(private readonly authService: AuthService) {
|
||||
super({
|
||||
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
|
||||
secretOrKeyProvider: '4557C0D7-DFB0-40DA-BF83-91A75103F7A9', //secretOrKey
|
||||
secretOrKey: '4557C0D7-DFB0-40DA-BF83-91A75103F7A9',
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@ import { Module } from '@nestjs/common';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm'; // <-- importe aqui
|
||||
import { UsersService } from './users.service';
|
||||
import { UserRepository } from './UserRepository';
|
||||
|
||||
import { AuthenticateUserService } from '../auth/authenticate-user.service';
|
||||
import { ResetPasswordService } from './reset-password.service';
|
||||
import { ChangePasswordService } from './change-password.service';
|
||||
|
||||
@@ -2,6 +2,8 @@ import { Injectable } from '@nestjs/common';
|
||||
import { AuthenticateUserService } from '../auth/authenticate-user.service';
|
||||
import { ResetPasswordService } from './reset-password.service';
|
||||
import { ChangePasswordService } from './change-password.service';
|
||||
import { AuthenticateUserCommand } from '../auth/authenticate-user.command';
|
||||
|
||||
|
||||
|
||||
@Injectable()
|
||||
@@ -13,9 +15,9 @@ export class UsersService {
|
||||
) {}
|
||||
|
||||
async authenticate(user: { userName: string; password: string }) {
|
||||
return this.authenticateUserService.execute(user.userName, user.password);
|
||||
const command = new AuthenticateUserCommand(user.userName, user.password);
|
||||
return this.authenticateUserService.execute(command);
|
||||
}
|
||||
|
||||
async resetPassword(user: { document: string; email: string }) {
|
||||
return this.resetPasswordService.execute(user.document, user.email);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user