Atualização repositorio

This commit is contained in:
eduardoestevao-appsoluti
2025-03-27 19:29:17 -03:00
parent b104682e1d
commit 41e56dda12
70 changed files with 15389 additions and 125 deletions

View File

@@ -0,0 +1,72 @@
/* eslint-disable prettier/prettier */
/* eslint-disable @typescript-eslint/no-unused-vars */
import {
Body,
Controller,
HttpException,
HttpStatus,
Post,
} from '@nestjs/common';
import { AuthService } from './auth.service';
import { UsersService } from '../users/users.service';
import { UserModel } from 'src/core/models/user.model';
import { ResultModel } from 'src/core/models/result.model';
import { ResetPasswordModel } from 'src/core/models/reset-password.model';
import { ChangePasswordModel } from 'src/core/models/change-password.model';
@Controller('api/v1/auth')
export class AuthController {
constructor(
private usersService: UsersService,
private authService: AuthService,
) { }
@Post('login')
async login(@Body() model: UserModel): Promise<any> {
const user = await this.usersService.authenticate(model);
if (!user)
throw new HttpException(
new ResultModel(false, 'Usuário ou senha inválidos.', null, null),
HttpStatus.UNAUTHORIZED,
);
const token = await this.authService.createToken(
user.id,
user.sellerId,
user.username,
user.email,
user.storeId
);
return {
id: user.id,
sellerId: user.sellerId,
name: user.name,
username: user.name,
storeId: user.storeId,
email: user.email,
token: token,
};
}
@Post('reset-password')
async resetPassword(@Body() resetPassword: ResetPasswordModel) {
const response = await this.usersService.resetPassword(resetPassword);
if (response == null) {
throw new HttpException('Usuário não foi encontrado', HttpStatus.NOT_FOUND);
}
return { message: 'Senha alterada com sucesso! Foi enviado email com a nova senha!' };
}
@Post('change-password')
async changePassword(@Body() changePassword: ChangePasswordModel) {
const response = await this.usersService.changePassword(changePassword);
if (response == null) {
throw new HttpException('Usuário não foi encontrado', HttpStatus.NOT_FOUND);
}
return { message: 'Senha alterada com sucesso!' };
}
}

View File

@@ -0,0 +1,26 @@
/* 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 { PassportModule } from '@nestjs/passport';
import { UsersModule } from '../users/users.module';
@Module({
imports: [
UsersModule,
PassportModule.register({
defaultStrategy: 'jwt',
}),
JwtModule.register({
secret: '4557C0D7-DFB0-40DA-BF83-91A75103F7A9',
signOptions: {
expiresIn: 3600,
},
}),
],
controllers: [AuthController],
providers: [AuthService],
exports: [AuthService],
})
export class AuthModule {}

View File

@@ -0,0 +1,32 @@
/* eslint-disable prettier/prettier */
/* eslint-disable @typescript-eslint/no-unused-vars */
import { Injectable } from '@nestjs/common';
import { JwtService, JwtSignOptions } from '@nestjs/jwt';
import { UsersService } from '../users/users.service';
import { JwtPayload } from '../models/jwt-payload.model';
@Injectable()
export class AuthService {
constructor(
private readonly usersService: UsersService,
private readonly jwtService: JwtService,
) {}
async createToken(id: number, sellerId: number, username: string, email: string, storeId: string) {
const user: JwtPayload = {
id: id,
sellerId: sellerId,
storeId: storeId,
username: username,
email: email,
};
const options: JwtSignOptions = { expiresIn: '8h' };
return this.jwtService.sign(user, options);
}
async validateUser(payload: JwtPayload): Promise<any> {
//return await this.accountService.findOneByUsername(payload.username);
return payload;
}
}

View File

@@ -0,0 +1,9 @@
/* eslint-disable prettier/prettier */
export interface JwtPayload {
id: number;
sellerId: number;
storeId: string;
username: string;
email: string;
}

View File

@@ -0,0 +1,24 @@
/* eslint-disable @typescript-eslint/no-unused-vars */
import { 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';
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor(private readonly authService: AuthService) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKeyProvider: '4557C0D7-DFB0-40DA-BF83-91A75103F7A9', //secretOrKey
});
}
async validate(payload: JwtPayload) {
const user = await this.authService.validateUser(payload);
if (!user) {
throw new UnauthorizedException();
}
return user;
}
}

View File

@@ -0,0 +1,10 @@
/* eslint-disable @typescript-eslint/no-unused-vars */
import { Module } from '@nestjs/common';
import { UsersService } from './users.service';
@Module({
imports: [],
providers: [UsersService],
exports: [UsersService],
})
export class UsersModule {}

View File

@@ -0,0 +1,18 @@
import { Test, TestingModule } from '@nestjs/testing';
import { UsersService } from './users.service';
describe('UsersService', () => {
let service: UsersService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [UsersService],
}).compile();
service = module.get<UsersService>(UsersService);
});
it('should be defined', () => {
expect(service).toBeDefined();
});
});

View File

@@ -0,0 +1,152 @@
/* eslint-disable prettier/prettier */
/* eslint-disable @typescript-eslint/no-unused-vars */
import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { DataSource } from 'typeorm';
import md5 = require('md5');
import { Guid } from "guid-typescript";
import { typeOrmConfig } from 'src/core/configs/typeorm.config';
import { UserModel } from 'src/core/models/user.model';
@Injectable()
export class UsersService {
async authenticate(user: any): Promise<any> {
const dataSource = new DataSource(typeOrmConfig);
await dataSource.initialize();
const queryRunner = dataSource.createQueryRunner();
await queryRunner.connect();
try {
const sql = `SELECT PCEMPR.MATRICULA AS "id"
,PCEMPR.NOME AS "name"
,PCEMPR.CODUSUR AS "sellerId"
,PCEMPR.CODFILIAL AS "storeId"
,PCEMPR.EMAIL AS "email"
,PCEMPR.DTDEMISSAO as "dataDesligamento"
,PCEMPR.SITUACAO as "situacao"
FROM PCEMPR
WHERE PCEMPR.USUARIOBD = '${user.userName}'
AND PCEMPR.SENHABD = CRYPT('${user.password.toUpperCase()}', PCEMPR.USUARIOBD) `;
const users = await queryRunner.manager.query(sql);
if (users.length == 0) {
return null;
}
const userDb = users[0];
if ( userDb.dataDesligamento !== null ) {
throw new HttpException('Usuário desligado da empresa, login não permitido!', HttpStatus.FORBIDDEN);
}
if ( userDb.situacao == 'I' ) {
throw new HttpException('Usuário inativo, login não permitido!', HttpStatus.FORBIDDEN);
}
return userDb;
} finally {
await queryRunner.release();
await dataSource.destroy();
}
}
async resetPassword(user: any): Promise<any> {
const dataSource = new DataSource(typeOrmConfig);
await dataSource.initialize();
const queryRunner = dataSource.createQueryRunner();
await queryRunner.connect();
await queryRunner.startTransaction();
try {
let sql =
'SELECT PCUSUARI.CODUSUR as "sellerId" ' +
' ,PCUSUARI.NOME as "name" ' +
' ,PCUSUARI.EMAIL as "email" ' +
' FROM PCUSUARI ' +
` WHERE REGEXP_REPLACE(PCUSUARI.CPF, '[^0-9]', '') = REGEXP_REPLACE(:1, '[^0-9]', '') ` +
` AND PCUSUARI.EMAIL = :2 `;
const users = await queryRunner.manager.query(sql, [
user.document,
user.email,
]);
if (users.length == 0) {
return null;
}
const guid = Guid.create();
console.log(guid.toString());
const password = guid.toString().substring(0, 8);
const newPassword = md5(password).toUpperCase();
console.log("Senha:" + newPassword)
sql = `UPDATE PCUSUARI SET ` +
` SENHALOGIN = :1 ` +
`WHERE CODUSUR = :2`;
await queryRunner.manager.query(sql, [newPassword, users[0].sellerId]);
const sqlEmail = `INSERT INTO CORRESPONDENCIAS ( CORRESPONDENCIA_ID, DTINCLUSAO, TITULO, MENSAGEM, EMAIL, DESTINATARIO )
VALUES ( SEQ_CORRESPONDENCIAS.NEXTVAL, SYSDATE, 'Alteração de email - CoteLivia',
'Sua senha para acesso ao portal COTELIVIA é ${password}', '${users[0].email}', '${users[0].email}' )`;
await queryRunner.manager.query(sqlEmail);
await queryRunner.commitTransaction();
const userDb = users[0];
return userDb;
} catch (error) {
await queryRunner.rollbackTransaction();
console.log(error);
throw new Error(error);
}
finally {
await queryRunner.release();
await dataSource.destroy();
}
}
async changePassword(user: any): Promise<any> {
const dataSource = new DataSource(typeOrmConfig);
await dataSource.initialize();
const queryRunner = dataSource.createQueryRunner();
await queryRunner.connect();
await queryRunner.startTransaction();
console.log(JSON.stringify(user));
try {
let sql =
'SELECT PCUSUARI.CODUSUR as "sellerId" ' +
' ,PCUSUARI.NOME as "name" ' +
' ,PCUSUARI.EMAIL as "email" ' +
' FROM PCUSUARI ' +
` WHERE PCUSUARI.CODUSUR = :1` +
` AND PCUSUARI.SENHALOGIN = :2 `;
const users = await queryRunner.manager.query(sql, [
user.id,
md5(user.password).toUpperCase(),
]);
if (users.length == 0) {
return null;
}
sql = `UPDATE PCUSUARI SET ` +
` SENHALOGIN = :1 ` +
`WHERE CODUSUR = :2`;
await queryRunner.manager.query(sql, [md5(user.newPassword).toUpperCase(), users[0].sellerId]);
await queryRunner.commitTransaction();
const userDb = users[0];
return userDb;
} catch (error) {
await queryRunner.rollbackTransaction();
console.log(error);
throw new Error(error);
}
finally {
await queryRunner.release();
await dataSource.destroy();
}
}
}