nestjs 实现用户注册、登录和验证功能 其中控制器的登录接口要求使用@body() 装饰器
时间: 2024-03-12 13:49:44 浏览: 16
好的,下面是一个使用NestJS实现用户注册、登录和验证功能的示例,其中控制器的登录接口使用了@Body()装饰器。
首先,需要安装相关的依赖:
```
npm install @nestjs/common @nestjs/jwt bcryptjs
```
然后,创建一个User类,用于描述用户对象:
```typescript
export class User {
id: number;
username: string;
password: string;
}
```
创建一个AuthService,用于处理用户数据的增删改查和生成JWT:
```typescript
import { Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import * as bcrypt from 'bcryptjs';
import { User } from './user';
@Injectable()
export class AuthService {
private readonly users: User[] = [];
constructor(private readonly jwtService: JwtService) {}
async register(user: User): Promise<User> {
const salt = await bcrypt.genSalt();
const hash = await bcrypt.hash(user.password, salt);
const createdUser = {
id: this.users.length + 1,
username: user.username,
password: hash,
};
this.users.push(createdUser);
return createdUser;
}
async login(user: User): Promise<string | undefined> {
const existingUser = this.users.find(u => u.username === user.username);
if (existingUser && await bcrypt.compare(user.password, existingUser.password)) {
const payload = { username: existingUser.username };
return this.jwtService.sign(payload);
}
return undefined;
}
async validateUser(username: string, password: string): Promise<User | undefined> {
const user = this.users.find(u => u.username === username);
if (user && await bcrypt.compare(password, user.password)) {
return user;
}
return undefined;
}
}
```
接下来,创建一个AuthController,用于处理用户注册、登录和验证的接口:
```typescript
import { Controller, Post, Body } from '@nestjs/common';
import { AuthService } from './auth.service';
import { User } from './user';
@Controller('auth')
export class AuthController {
constructor(private readonly authService: AuthService) {}
@Post('/register')
async register(@Body() user: User): Promise<User> {
return this.authService.register(user);
}
@Post('/login')
async login(@Body() user: User): Promise<{ accessToken: string } | undefined> {
const token = await this.authService.login(user);
if (token) {
return { accessToken: token };
}
return undefined;
}
}
```
最后,将AuthService和AuthController添加到AppModule中:
```typescript
import { Module } from '@nestjs/common';
import { JwtModule } from '@nestjs/jwt';
import { AuthService } from './auth.service';
import { AuthController } from './auth.controller';
@Module({
imports: [
JwtModule.register({
secret: 'secret_key',
signOptions: { expiresIn: '1h' },
}),
],
providers: [AuthService],
controllers: [AuthController],
})
export class AppModule {}
```
这样,就可以使用NestJS实现用户注册、登录和验证功能了。在控制器的登录接口中,使用@Body()装饰器可以将请求体中的数据解析为一个User对象,方便处理。同时,可以使用JwtModule生成和验证JWT,加强安全性。