How to hash password before inserting? - node.js

I am using Nest.Js with TypeORM and I want to hash my password before persisting into the DB.
I tried using the event decorator #BeforeInsert() however it wasn't working for me but later I found that it was not working because I was taking an DTO as an input.
user.controller.ts
#Post()
async create(#Body() data: CreateUserDto, #Res() res) {
// if user already exist
const isUserExist = await this.service.findByEmail(data.email);
if (isUserExist) {
throw new BadRequestException('Email already exist');
}
// insert user
this.service.create(data);
// send response
return res.status(201).json({
statusCode: 201,
message: 'User added Successfully',
});
}
user.service.ts
create(data: CreateUserDto) {
return this.userRepository.save(data)
}
So, I was basically using an DTO to save the data. That's why it was not working.
But what I want to do is map the DTO to user object. So, This is what I did.
#Post()
async create(#Body() data: CreateUserDto, #Res() res) {
// Create User object
const user = new User();
// Map DTO to User object
for (const [key, value] of Object.entries(data)) {
user[key] = value;
}
// if user already exist
const isUserExist = await this.service.findByEmail(user.email);
if (isUserExist) {
throw new BadRequestException('Email already exist');
}
// insert user
this.service.create(user);
// send response
return res.status(201).json({
statusCode: 201,
message: 'User added Successfully',
});
}
create-user.dto.ts
import { IsEmail, IsNotEmpty, IsString } from 'class-validator';
import { ApiProperty } from '#nestjs/swagger';
export class CreateUserDto {
#IsNotEmpty()
#IsString()
#ApiProperty()
readonly firstName: string;
#IsNotEmpty()
#IsString()
#ApiProperty()
readonly lastName: string;
#IsNotEmpty()
#IsString()
#IsEmail()
#ApiProperty()
readonly email: string;
#IsNotEmpty()
#IsString()
#ApiProperty()
readonly password: string;
}
Is there any better approach for this? Because currently I have to write the code in every method to map it.

I would first move all the logic from my controller into the service. This would allow you to reuse the logic in other places, if there are any (since you prefer to have that service class).
Personally, I would avoid writing smart code because it saves me 2 or 3 lines of code. When someone else than you would have to review/refactor it would be a pain in the back. Just write something that's easy to understand.
Third, I would avoid using magic things like beforeInsert. Yeah, it might look smart but you don't make it clear how the pass is generated.
If your entity has the same fields as your DTO what's then the benefit of having the dto. Personally I would avoid exposing entity's password property. Instead, I would have a changePassword(generator: IUserPassGenerator) method in the entity. As for checking the pass, I would have somethingnlike verifyPass(validator: IPassChecker) method.
Another thing that I would avoid would be setters or public props mainly because it might cause your entity to enter into an invalid state. In your case e.g. someone else might change the password property with a md5 hash. After all, they can even change it with an unhashed string.

We can easily map Plain Object Literal to Class Instances by using 'class-transformer' package
Answer:
async create(#Body() data: CreateUserDto, #Res() res) {
const user = plainToClass(User, data)
}

this is a valid approach.
What you can do is extract this logic from the create method and create some kind of Builder object to create User objects from the DTO and vice-versa and call the builder where you need it.

Related

Class-Validator (Node.js) Get another property value within custom validation

At the moment, I have a very simple class-validator file with a ValidationPipe in Nest.js as follows:
import {
IsDateString,
IsEmail,
IsOptional,
IsString,
Length,
Max,
} from 'class-validator';
export class UpdateUserDto {
#IsString()
id: string;
#Length(2, 50)
#IsString()
firstName: string;
#IsOptional()
#Length(2, 50)
#IsString()
middleName?: string;
#Length(2, 50)
#IsString()
lastName: string;
#IsEmail()
#Max(255)
email: string;
#Length(8, 50)
password: string;
#IsDateString()
dateOfBirth: string | Date;
}
Lets say in the above "UpdateUserDto," the user passes an "email" field. I want to build a custom validation rule through class-validator such that:
Check if email address is already taken by a user from the DB
If the email address is already in use, check if the current user (using the value of 'id' property) is using it, if so, validation passes, otherwise, if it is already in use by another user, the validation fails.
While checking if the email address is already in use is a pretty simple task, how would you be able to pass the values of other properties within the DTO to a custom decorator #IsEmailUsed
It was pretty simple to solve, I solved it by creating a custom class-validation Decorator as below:
import { PrismaService } from '../../prisma/prisma.service';
import {
registerDecorator,
ValidationOptions,
ValidatorConstraint,
ValidatorConstraintInterface,
ValidationArguments,
} from 'class-validator';
import { Injectable } from '#nestjs/common';
#ValidatorConstraint({ name: 'Unique', async: true })
#Injectable()
export class UniqueConstraint implements ValidatorConstraintInterface {
constructor(private readonly prisma: PrismaService) {}
async validate(value: any, args: ValidationArguments): Promise<boolean> {
const [model, property = 'id', exceptField = null] = args.constraints;
if (!value || !model) return false;
const record = await this.prisma[model].findUnique({
where: {
[property]: value,
},
});
if (record === null) return true;
if (!exceptField) return false;
const exceptFieldValue = (args.object as any)[exceptField];
if (!exceptFieldValue) return false;
return record[exceptField] === exceptFieldValue;
}
defaultMessage(args: ValidationArguments) {
return `${args.property} entered is not valid`;
}
}
export function Unique(
model: string,
uniqueField: string,
exceptField: string = null,
validationOptions?: ValidationOptions,
) {
return function (object: any, propertyName: string) {
registerDecorator({
target: object.constructor,
propertyName: propertyName,
options: validationOptions,
constraints: [model, uniqueField, exceptField],
validator: UniqueConstraint,
});
};
}
However, to allow DI to that particular Decorator, you need to also add this to your main.ts bootstrap function:
async function bootstrap() {
const app = await NestFactory.create(AppModule);
...
// Line below needs to be added.
useContainer(app.select(AppModule), { fallbackOnErrors: true });
...
}
Also, make sure to import the "Constraint" in the app module:
#Module({
imports: ...,
controllers: [AppController],
providers: [
AppService,
PrismaService,
...,
// Line below added
UniqueConstraint,
],
})
export class AppModule {}
Finally, add it to your DTO as such:
export class UpdateUserDto {
#IsString()
id: string;
#IsEmail()
#Unique('user', 'email', 'id') // Adding this will check in the user table for a user with email entered, if it is already taken, it will check if it is taken by the same current user, and if so, no issues with validation, otherwise, validation fails.
email: string;
}
Luckily for us, the class-validator provides a very handy useContainer function, which allows setting the container to be used by the class-validor library.
So add this code in your main.ts file (app variable is your Nest application instance):
useContainer(app.select(AppModule), { fallbackOnErrors: true });
It allows the class-validator to use the NestJS dependency injection container.
#ValidatorConstraint({ name: 'emailId', async: true })
#Injectable()
export class CustomEmailvalidation implements ValidatorConstraintInterface {
constructor(private readonly prisma: PrismaService) {}
async validate(value: string, args: ValidationArguments): Promise<boolean> {
return this.prisma.user
.findMany({ where: { email: value } })
.then((user) => {
if (user) return false;
return true;
});
}
defaultMessage(args: ValidationArguments) {
return `Email already exist`;
}
}
Don't forget to declare your injectable classes as providers in the appropriate module.
Now you can use your custom validation constraint. Simply decorate the class property with #Validate(CustomEmailValidation) decorator:
export class CreateUserDto {
#Validate(customEmailValidation)
email: string;
name: string;
mobile: number;
}
If the email already exists in the database, you should get an error with the default message "Email already exists". Although using #Validate() is fine enough, you can write your own decorator, which will be much more convenient. Having written Validator Constraint is quick and easy. We need to just write decorator factory with registerDecorator() function.
export function Unique(validationOptions?: ValidationOptions) {
return function (object: any, propertyName: string) {
registerDecorator({
target: object.constructor,
propertyName: propertyName,
options: validationOptions,
validator: CustomEmailvalidation,
});
};
}
As you can see, you can either write new validator logic or use written before validator constraint (in our case - Unique class).
Now we can go back to our User class and use the #Unique validator instead of the #Validate(CustomEmailValidation) decorator.
export class CreateUserDto {
#Unique()
email: string;
name: string;
mobile: number;
}
I think your first use case (Check if email address is already taken by a user from the DB), can be solved by using custom-validator
For the second one there is no option to get the current user before the validation. Suppose you are getting the current user using the #CurrentUser decorator. Then once the normal dto validation is done, you need to check inside the controller or service if the current user is accessing your resource.

How to check reference when inserting in MongoDB (typegraphql, typegoose)?

Let say I have a simple collection events created by TypeGraphql and Typegoose which stores objects like:
{ _id: ObjectId(...), name: 'SomeEvent', category: ObjectId('...') }
and corresponding type:
#ObjectType()
export class Event {
#Field(() => ID)
_id!: Types.ObjectId
#prop({ ref: 'Category' })
#Field(() => Category)
category!: Ref<Category>
#prop()
#Field()
name!: string
}
I have also collection categories which contains right now only _id and name.
Now I want to insert some Event to database. Is it possible to automatically check if categoryId provided in input exist in collection categories and if it does not, throw an error? Right now, event can be added with anything in category field and next when I try to get it by query it throws an error that category cannot be resolved because there is no category with this ID. I know, that I can check it manually during adding event but if I have more fields like that it will be problematic.
With the help of Martin Devillers answer I was able to write a validator to validate referenced documents using class-validator with typegoose.
This is my refdoc.validator.ts:
import { ValidationArguments, ValidatorConstraint, ValidatorConstraintInterface } from "class-validator";
import { Injectable } from "#nestjs/common";
import { getModelForClass } from "#typegoose/typegoose";
#ValidatorConstraint({ name: "RefDoc", async: true })
#Injectable()
export class RefDocValidator implements ValidatorConstraintInterface {
async validate(refId: string, args: ValidationArguments) {
const modelClass = args.constraints[0];
return getModelForClass(modelClass).exists({ _id: refId })
}
defaultMessage(): string {
return "Referenced Document not found!";
}
}
Then I can apply it on the DTO or model with the #Validate-Decorator. The Argument I'm passing in is the typegoose model.
#Validate(RefDocValidator, [Costcenter])
costcenterId: string;
Seems to be working for me, I'm open for any improvements..
Edit: Even better with custom decorator, as Martin Devillers suggested:
refdoc.validator.ts
import { registerDecorator, ValidationArguments, ValidationOptions, ValidatorConstraint, ValidatorConstraintInterface } from "class-validator";
import { Injectable } from "#nestjs/common";
import { getModelForClass } from "#typegoose/typegoose";
#ValidatorConstraint({ name: "RefDoc", async: true })
#Injectable()
export class RefDocValidator implements ValidatorConstraintInterface {
async validate(refId: string, args: ValidationArguments) {
const modelClass = args.constraints[0];
return getModelForClass(modelClass).exists({ _id: refId })
}
defaultMessage(): string {
return "Referenced Document not found!";
}
}
export function RefDocExists(modelClass: any, validationOptions?: ValidationOptions) {
return function (object: Object, propertyName: string) {
registerDecorator({
name: 'RefDocExists',
target: object.constructor,
propertyName: propertyName,
constraints: [modelClass],
options: validationOptions,
validator: RefDocValidator,
});
};
}
Then you can use it on the DTO like:
#ApiProperty()
#IsNotEmpty()
//#Validate(RefDocValidator, [Costcenter]) old
#RefDocExists(Costcenter) //new
costcenterId: string;
Out of the box, neither MongoDB nor mongoose nor typegoose offer any automated referential integrity checks.
At the database level, this feature doesn't exist (which is also one of the fundamental differences between a database like MongoDB and SQL Server/Oracle).
However, at the application level, you can achieve this behavior in various ways:
Middleware. Mongoose middleware allows you add generalized behavior to your models. This is useful if you're inserting documents in your EventModel in various places in your codebase and don't want to repeat your validation logic. For example:
EventModel.path('category').validate(async (value, respond) => {
const categoryExists = await CategoryModel.exists({ _id: value })
respond(categoryExists)
})
Mongoose plugins. A plugin like mongoose-id-validator allows you to add the above behavior to any type of document reference in all your schemas.
Manually. Probably the least favorite option, but I'm mentioning it for completeness sake: with mongoose's Model.exists() you can achieve this with a one-liner like: const categoryExists = await CategoryModel.exists({ _id: event.category })
To reiterate: all the above options are stopgaps. It's always possible for someone to go directly in your database and break referential integrity anyway.

How to use DTO in services file of nestjs app

I want to fetch data of a particular person from mongodb on the basis of username and password values,but i got all the data of db instead of particular person which i passed in username and password.
Here is the code of DTO:
import {IsString, IsInt,IsEmail,IsNotEmpty, IsNumberString} from 'class-validator';
export class LoginDto {
#IsEmail()
username: string;
#IsNumberString()
password: string;
}
Here is the code of Services:
async loginsys(credentials: LoginDto): Promise<any> {
const cred = await this.student.find({ credentials }).exec();
return cred;
}
Here is the code of controller:
#Post('login')
log(#Body('credentials') credentials: LoginDto): any {
return this.crudservice.loginsys(credentials);
}
If you want to get exactly one entity, you can use findOne instead of find:
return this.student.findOne(credentials)
find should work if you pass your query to where:
find({where: credentials})`
exec() is not necessary.

DTO in nest js accepting more parameter as compared to DTO

I have a DTO
export class UpdateUserRoleDTO {
#ApiProperty()
#IsNotEmpty()
readonly userId:number;
#ApiProperty()
#IsNotEmpty()
#IsNumber()
readonly roleId: number;
}
My controller looks like this
#UsePipes(new ValidationPipe())
#Post('/update')
async updateUser(#Body() updateUserDto: UpdateUserDTO): Promise<User> {
return await this.userService.updateUser(updateUserDto);
}
Whenever client sends a request with the following payload
payloadObj = {
userId : 1,
roleId : 1,
xyz : 'assddcds',
someotherkey : 'fsdvs'
}
It's hitting my service file .I want to avoid this make sure only parameter mentioned in DTO should be passed else it should give 400
given your code I'd pass the whitelist option set to true to the ValidationPipe you're instantiating, like so in your controller:
controller.ts
#UsePipes(new ValidationPipe({ whitelist: true }))
#Post('/update')
async updateUser(#Body() updateUserDto: UpdateUserDTO): Promise<User> {
return await this.userService.updateUser(updateUserDto);
}
This should do the work.
Let me know if it helps, otherwise don't hesitate to comment & share your findings ;)

#Get DTO with multiple parameters in NestJs

I'm trying to create a controller action in NestJS accessible via GET HTTP request which receives two params but they are undefined for some reason.
How to fix it?
#Get('/login')
login(#Param() params: LoginUserDto) {
console.log(params)
return 'OK'
}
import { ApiModelProperty } from '#nestjs/swagger';
export class LoginUserDto {
#ApiModelProperty()
readonly userName: string;
#ApiModelProperty()
readonly password: string;
}
In Browser
localhost:3001/Products/v1/user2
Controller like this:
#Controller('Products')
export class CrashesController {
constructor(private readonly crashesService: CrashesService) { }
#Get('/:version/:user')
async findVersionUser(#Param('version') version: string, #Param('user') user: string): Promise<Crash[]> {
return this.crashesService.findVersionUser(version, user);
}
}
Nest doesn't support the ability to automatically convert Get query params into an object in this way. It's expected that you would pull out the params individually by passing the name of the param to the #Param decorator.
Try changing your signature to:
login(#Param('userName') userName: string, #Param('password') password: string)
If you want to receive an object instead consider switching to using Post and passing the object in the request body (which makes more sense to me for a login action anyways).
Right now i am using nestJs on 7.0.0 and if you do this:
#Get('/paramsTest3/:number/:name/:age')
getIdTest3(#Param() params:number): string{
console.log(params);
return this.appService.getMultipleParams(params);
}
the console.log(params) result will be(the values are only examples):
{ number:11, name: thiago, age: 23 }
i hope that after all that time i've been helpful to you in some way !
Let's say you need to pass a one required parameter named id you can send it through header params, and your optional parameters can be sent via query params;
#Get('/:id')
findAll(
#Param('id') patientId: string,
#Query() filter: string,
): string {
console.log(id);
console.log(filter);
return 'Get all samples';
}
#Get('/login/:email/:password')
#ApiParam({name:'email',type:'string'})
#ApiParam({name:'password',type:'string'})
login(#Param() params: string[]) {
console.log(params)
return 'OK'
}
Output
{email:<input email >,password:<input password>}
You can get multiple params and map them to your dto in this way:
#Get('/login')
login(#Param() { userName, password }: LoginUserDto) {
console.log({ userName});
console.log({ password });
return 'OK'
}

Resources