auth in nestjs

Auth in nestjs

Use bcrypt to encryption password in backend

1
2
3
4
5
6
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

Usage

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
// UsersController
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
};
}

// UsersService
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;
}

本文作者: 孟 虎
本文链接: https://menghu1994.github.io/blog/2023/10/Nodejs/NestJs/auth/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!