nestjs 用户 注册 登录 验证模块 代码实现
时间: 2023-07-25 22:35:06 浏览: 43
好的,以下是一个基本的 NestJS 用户注册、登录、验证模块的代码实现:
首先,我们需要安装一些必要的库:
```bash
npm install @nestjs/passport passport passport-local bcryptjs
```
然后,我们可以创建一个 `auth` 模块:
```bash
nest g module auth
```
接下来,我们可以创建一些必要的服务和控制器:
```bash
nest g service auth/auth
nest g controller auth/auth
```
在 `auth.service.ts` 中,我们可以实现用户注册和验证逻辑:
```typescript
import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { User } from '../users/user.interface';
import * as bcrypt from 'bcryptjs';
@Injectable()
export class AuthService {
constructor(@InjectModel('User') private readonly userModel: Model<User>) {}
async validateUser(username: string, password: string): Promise<any> {
const user = await this.userModel.findOne({ username });
if (user && bcrypt.compareSync(password, user.password)) {
const { password, ...result } = user;
return result;
}
return null;
}
async register(user: User): Promise<any> {
const salt = bcrypt.genSaltSync();
user.password = bcrypt.hashSync(user.password, salt);
const newUser = new this.userModel(user);
return await newUser.save();
}
}
```
在 `auth.controller.ts` 中,我们可以创建一个用于注册新用户的端点:
```typescript
import { Controller, Post, Body } from '@nestjs/common';
import { AuthService } from './auth.service';
import { User } from '../users/user.interface';
@Controller('auth')
export class AuthController {
constructor(private readonly authService: AuthService) {}
@Post('register')
async register(@Body() user: User): Promise<any> {
return await this.authService.register(user);
}
}
```
然后,我们需要在 `users` 模块中创建一个用户接口:
```bash
nest g interface users/user
```
```typescript
export interface User {
username: string;
password: string;
}
```
最后,我们需要在 `app.module.ts` 中导入 `AuthModule`:
```typescript
import { Module } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
import { AuthModule } from './auth/auth.module';
import { UsersModule } from './users/users.module';
@Module({
imports: [
MongooseModule.forRoot('mongodb://localhost/nestjs'),
AuthModule,
UsersModule,
],
})
export class AppModule {}
```
现在我们就可以通过发送 POST 请求到 `/auth/register` 端点来注册新用户了。