vinicius gati
vinicius gati

Reputation: 419

Strong Parameters on nestjs

Hi im new to nestjs and ts to, i am trying to do a user registration using nestjs and it is working fine, dto's looks like the way to go to flow data from web to any datasource on nest.

The problem is that i have a dto with 2 fields login and password and my database schema has 3, login, password and admin(boolean).

If i do a request and validate this login and password and they are fine i just save it to the database, no problema until now.

The problem is that using DTO if i pass the admin with true the admin data flows directly to the database, ok i know i have to be responsible and remover this from the object but im kind of concerned with this being the default behavior because this can lead very easily to a security breach.

My code is:


let body = {
    login: 'vinicius',
    password: 'keyboardcat',
    admin: 'true'
}

// DTO
class Login {
    login!: string;
    password!: string;
}

let data = body as Login;

console.log(JSON.stringify(data)); 
// => {"login":"vinicius","password":"keyboardcat","admin":"true"}
// note that the admin is on the object even so its not on DTO

// this destructuring achieves the desired behavior
const { admin, ...desiredData } = body;

console.log(JSON.stringify(desiredData));
// => {"login":"vinicius","password":"keyboardcat"} // this is the desired

The question is, how you guys deal with this? Is there any better way of doing this without, i mean, without too much deviation from the default DTO that everyone uses?

Upvotes: 0

Views: 1090

Answers (1)

RalphJS
RalphJS

Reputation: 533

I think it is as simple as adding a parameter to the class with the @IsBolean decorator

@IsBoolean()
public admin!: boolean;

Maybe you can take a look to the class-validator documentation wich is the library that NestJS uses to defining DTOs

Edit: with the changes you did in your question I understood perfectly now in the DTO part you can't do what you are planning as it is like a blueprint of the operation in the DTO you can do some form changes that comes in the body like parsing a string or converting a nested object to an specific class before the operation, depending on the complexity you want to add youu can have two aproaches: object destructuring(the one that is in the example) or create a custom pipe that does that transformation, I would recomend you use destructuring, I don't see any problem in that.

Upvotes: 2

Related Questions