Skip to content

Commit

Permalink
Merge pull request #146 from wandersonDeve/main
Browse files Browse the repository at this point in the history
Atualização da função que valida o cpf e cnpj
  • Loading branch information
wandersonDeve authored Oct 1, 2023
2 parents 456a537 + bcb2cf8 commit beb8bfd
Show file tree
Hide file tree
Showing 5 changed files with 137 additions and 76 deletions.
106 changes: 106 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@
"bcrypt": "^5.0.1",
"class-transformer": "^0.5.1",
"class-validator": "^0.13.2",
"cpf-cnpj-validator": "^1.0.3",
"handlebars": "^4.7.7",
"nodemailer": "^6.9.1",
"passport": "^0.6.0",
Expand Down
7 changes: 2 additions & 5 deletions src/modules/upload/upload.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,7 @@ import {
} from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { FileInterceptor } from '@nestjs/platform-express';
import {
ApiBearerAuth,
ApiTags
} from '@nestjs/swagger';
import { ApiBearerAuth, ApiTags } from '@nestjs/swagger';
import { UploadSwagger } from 'src/shared/Swagger/decorators/upload/upload.swagger';
import { FileUploadService } from './upload.service';

Expand All @@ -22,7 +19,7 @@ export class UploadController {
constructor(private fileUploadService: FileUploadService) {}

@UploadSwagger()
@Post('')
@Post()
@UseInterceptors(FileInterceptor('file'))
async upload(@UploadedFile() file) {
const response = await this.fileUploadService.upload(file);
Expand Down
31 changes: 13 additions & 18 deletions src/modules/user/user.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,18 @@ import {
UseInterceptors,
} from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import {
ApiBearerAuth,
ApiTags,
} from '@nestjs/swagger';
import { FileInterceptor } from '@nestjs/platform-express';
import { ApiBearerAuth, ApiTags } from '@nestjs/swagger';
import { Request, Response } from 'express';
import { SwaggerCreateUser } from 'src/shared/Swagger/decorators/user/create-user.swagger.decorator';
import { SwaggerDeleteUser } from 'src/shared/Swagger/decorators/user/delete-user.swagger.decorator';
import { SwaggerGetUserAdm } from 'src/shared/Swagger/decorators/user/get-user-adm.swagger.decorator';
import { SwaggerGetUser } from 'src/shared/Swagger/decorators/user/get-user.swagger.decorator';
import { SwaggerRecoverEmail } from 'src/shared/Swagger/decorators/user/recover-by-email.swagger.decorator';
import { SwaggerUpdatePassAfterRecovery } from 'src/shared/Swagger/decorators/user/update-pass-after-email-recovery.swagger.decorator';
import { SwaggerUpdatePassword } from 'src/shared/Swagger/decorators/user/update-password.swagger.decorator';
import { SwaggerUpdateUser } from 'src/shared/Swagger/decorators/user/update-user.swagger.decorator';
import { SwaggerFindUsers } from 'src/shared/Swagger/decorators/user/view-users.swagger.decorator';
import { UsersEntity } from '../../database/entities/users.entity';
import { PageOptionsDto } from '../../shared/pagination';
import { LoggedAdmin } from '../auth/decorator/logged-admin.decorator';
Expand All @@ -31,9 +38,6 @@ import {
UpdateMyPasswordDto,
} from './dtos/update-my-password.dto';
import { UpdateUserDto } from './dtos/update-user.dto';

import { FileInterceptor } from "@nestjs/platform-express";

import {
CreateUserService,
DeleteUserService,
Expand All @@ -45,15 +49,6 @@ import {
} from './services';
import { ActivateUserService } from './services/activate-user.service';
import { UpdatePasswordService } from './services/update-password.service';
import { SwaggerCreateUser } from 'src/shared/Swagger/decorators/user/create-user.swagger.decorator';
import { SwaggerGetUser } from 'src/shared/Swagger/decorators/user/get-user.swagger.decorator';
import { SwaggerFindUsers } from 'src/shared/Swagger/decorators/user/view-users.swagger.decorator';
import { SwaggerGetUserAdm } from 'src/shared/Swagger/decorators/user/get-user-adm.swagger.decorator';
import { SwaggerUpdateUser } from 'src/shared/Swagger/decorators/user/update-user.swagger.decorator';
import { SwaggerDeleteUser } from 'src/shared/Swagger/decorators/user/delete-user.swagger.decorator';
import { SwaggerRecoverEmail } from 'src/shared/Swagger/decorators/user/recover-by-email.swagger.decorator';
import { SwaggerUpdatePassAfterRecovery } from 'src/shared/Swagger/decorators/user/update-pass-after-email-recovery.swagger.decorator';
import { SwaggerUpdatePassword } from 'src/shared/Swagger/decorators/user/update-password.swagger.decorator';

@ApiTags('User')
@Controller('user')
Expand Down Expand Up @@ -106,7 +101,7 @@ export class UserController {
@SwaggerGetUserAdm()
@UseGuards(AuthGuard())
@ApiBearerAuth()
async getOneUser(@Param("id") id: string, @LoggedUser() user: UsersEntity) {
async getOneUser(@Param('id') id: string, @LoggedUser() user: UsersEntity) {
return this.findOneUserService.execute(id);
}

Expand All @@ -127,7 +122,7 @@ export class UserController {
@SwaggerDeleteUser()
@UseGuards(AuthGuard())
@ApiBearerAuth()
async deleteUser(@Param("id") id: string, @LoggedUser() user: UsersEntity) {
async deleteUser(@Param('id') id: string, @LoggedUser() user: UsersEntity) {
return this.deleteUserService.execute(id);
}

Expand Down
68 changes: 15 additions & 53 deletions src/shared/validators/cnpj.validator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,64 +2,26 @@ import {
registerDecorator,
ValidationArguments,
ValidationOptions,
ValidatorConstraint,
ValidatorConstraintInterface,
} from 'class-validator';
import { cnpj, cpf } from 'cpf-cnpj-validator';

@ValidatorConstraint({ async: true })
export class isCNPJValidator implements ValidatorConstraintInterface {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
validate(cnpj: string, args: ValidationArguments) {
return isValidCNPJ(cnpj);
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
defaultMessage(args: ValidationArguments) {
return 'CNPJ $value is invalid';
}
}

export function IsCNPJ(params?: object, validationOptions?: ValidationOptions) {
return function (object?: object, propertyName?: string) {
export default function IsCPForCNPJ(validationOptions?: ValidationOptions) {
return function (object: any, propertyName: string) {
registerDecorator({
name: 'IsCPForCNPJ',
target: object.constructor,
propertyName,
propertyName: propertyName,
options: validationOptions,
constraints: [params],
validator: isCNPJValidator,
validator: {
validate(value: any) {
if (!value) return true;

return cpf.isValid(value) || cnpj.isValid(value);
},
defaultMessage(validationArguments?: ValidationArguments): string {
return `${validationArguments.property} must be a valid CPF or CNPJ document`;
},
},
});
};
}

/**
* Validates a CNPJ
* @param cnpj The CNPJ value to be validated
*/
export function isValidCNPJ(cnpj: string): boolean {
if (!/[\.\/\-]/g.test(cnpj)) return false;

const cleaned = cnpj.toString().replace(/[\.\/\-]/g, '');

if (!cleaned || cleaned.length !== 14 || /^(\d)\1+$/.test(cleaned)) {
return false;
}

let registration = cleaned.substr(0, 12);
registration += digit(registration);
registration += digit(registration);

return registration.substr(-2) === cleaned.substr(-2);
}

function digit(numbers: string): number {
let index = 2;

const sum = [...numbers].reverse().reduce((buffer, number) => {
buffer += Number(number) * index;
index = index === 9 ? 2 : index + 1;
return buffer;
}, 0);

const mod = sum % 11;

return mod < 2 ? 0 : 11 - mod;
}

0 comments on commit beb8bfd

Please sign in to comment.