nestjs 实现用户的注册登录 功能
时间: 2023-09-27 12:06:26 浏览: 69
要实现用户的注册和登录功能,可以按照以下步骤:
1. 安装 NestJS 和相关依赖
```
npm i --save @nestjs/passport @nestjs/jwt passport passport-local bcrypt
```
2. 创建用户模型
在 `src/auth` 目录下创建 `user.entity.ts` 文件,并定义用户模型。
```typescript
import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number;
@Column()
username: string;
@Column()
password: string;
}
```
3. 创建用户注册和登录服务
在 `src/auth` 目录下创建 `auth.service.ts` 文件,并定义用户注册和登录服务。
```typescript
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { User } from './user.entity';
import * as bcrypt from 'bcrypt';
@Injectable()
export class AuthService {
constructor(
@InjectRepository(User)
private readonly userRepository: Repository<User>,
) {}
async register(username: string, password: string): Promise<User> {
const hashedPassword = await bcrypt.hash(password, 10);
const user = this.userRepository.create({
username,
password: hashedPassword,
});
return this.userRepository.save(user);
}
async validateUser(username: string, password: string): Promise<User> {
const user = await this.userRepository.findOne({ username });
if (user && (await bcrypt.compare(password, user.password))) {
return user;
}
return null;
}
}
```
4. 创建认证策略
在 `src/auth` 目录下创建 `local.strategy.ts` 文件,并定义本地认证策略。
```typescript
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { Strategy } from 'passport-local';
import { AuthService } from './auth.service';
@Injectable()
export class LocalStrategy extends PassportStrategy(Strategy) {
constructor(private readonly authService: AuthService) {
super();
}
async validate(username: string, password: string): Promise<any> {
const user = await this.authService.validateUser(username, password);
if (!user) {
throw new UnauthorizedException();
}
return user;
}
}
```
5. 创建 JWT 认证模块
在 `src/auth` 目录下创建 `jwt-auth.module.ts` 文件,并定义 JWT 认证模块。
```typescript
import { Module } from '@nestjs/common';
import { AuthService } from './auth.service';
import { LocalStrategy } from './local.strategy';
import { JwtModule } from '@nestjs/jwt';
import { JwtStrategy } from './jwt.strategy';
import { PassportModule } from '@nestjs/passport';
@Module({
imports: [
PassportModule,
JwtModule.register({
secret: 'your-secret-key',
signOptions: { expiresIn: '1d' },
}),
],
providers: [AuthService, LocalStrategy, JwtStrategy],
exports: [AuthService],
})
export class JwtAuthModule {}
```
6. 创建 JWT 认证策略
在 `src/auth` 目录下创建 `jwt.strategy.ts` 文件,并定义 JWT 认证策略。
```typescript
import { Injectable } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { Strategy, ExtractJwt } from 'passport-jwt';
import { AuthService } from './auth.service';
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor(private readonly authService: AuthService) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: 'your-secret-key',
});
}
async validate(payload: any) {
return { userId: payload.sub, username: payload.username };
}
}
```
7. 创建认证控制器
在 `src/auth` 目录下创建 `auth.controller.ts` 文件,并定义认证控制器。
```typescript
import { Controller, Post, Request, UseGuards } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { AuthService } from './auth.service';
import { JwtAuthGuard } from './jwt-auth.guard';
import { LocalAuthGuard } from './local-auth.guard';
@Controller('auth')
export class AuthController {
constructor(private readonly authService: AuthService) {}
@UseGuards(LocalAuthGuard)
@Post('login')
async login(@Request() req) {
return this.authService.login(req.user);
}
@Post('register')
async register(@Request() req) {
const { username, password } = req.body;
return this.authService.register(username, password);
}
@UseGuards(JwtAuthGuard)
@Post('profile')
async profile(@Request() req) {
return req.user;
}
}
```
8. 创建本地认证守卫
在 `src/auth` 目录下创建 `local-auth.guard.ts` 文件,并定义本地认证守卫。
```typescript
import { Injectable } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
@Injectable()
export class LocalAuthGuard extends AuthGuard('local') {}
```
9. 创建 JWT 认证守卫
在 `src/auth` 目录下创建 `jwt-auth.guard.ts` 文件,并定义 JWT 认证守卫。
```typescript
import { Injectable } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {}
```
以上就是使用 NestJS 实现用户的注册登录功能的步骤。需要注意的是,在实际开发中,需要根据具体的需求进行相应的调整和扩展。