auth in nestjs
Auth in nestjs
Use bcrypt to encryption password in backend
| npm install --save @nestjs/passport passport passport-local // types npm install --save-dev @types/passport-local // mongoose npm install --save @nestjs/mongoose mongoose npm install @types/bcrypt bcrypt
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| constructor(private readonly usersService: UsersService) {} @Post('/signup') async addUser( @Body('password') userPassword: string, @Body('username') userName: string, ) { const saltOrRounds = 10; const hashedPassword = await bcrypt.hash(userPassword, saltOrRounds); const result = await this.usersService.insertUser( userName, hashedPassword, ); return { msg: 'User successfully registered', userId: result.id, userName: result.username }; }
constructor(@InjectModel('user') private readonly userModel: Model<User>) { async insertUser(userName: string, password: string) { const username = userName.toLowerCase(); const newUser = new this.userModel({ username, password, }); await newUser.save(); return newUser; }
|