nestjs 用户注册验证登录 功能
时间: 2023-07-21 19:22:35 浏览: 138
好的,关于 NestJS 的用户注册、验证和登录功能,可以通过以下步骤来实现:
1. 安装必要的依赖
在项目根目录下运行以下命令来安装必要的依赖:
```
npm install --save @nestjs/passport passport passport-local bcrypt
npm install --save-dev @types/passport-local
```
2. 创建用户模型
在 `src/auth` 目录下创建 `user.entity.ts` 文件,并定义用户模型,例如:
```typescript
import { BaseEntity, Entity, PrimaryGeneratedColumn, Column, Unique } from 'typeorm';
@Entity()
@Unique(['username'])
export class User extends BaseEntity {
@PrimaryGeneratedColumn()
id: number;
@Column()
username: string;
@Column()
password: string;
}
```
3. 创建用户注册 DTO
在 `src/auth/dto` 目录下创建 `auth.dto.ts` 文件,并定义用户注册 DTO,例如:
```typescript
export class AuthDto {
username: string;
password: string;
}
```
4. 创建用户认证服务
在 `src/auth` 目录下创建 `auth.service.ts` 文件,并定义用户认证服务,例如:
```typescript
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { User } from './user.entity';
import { AuthDto } from './dto/auth.dto';
import * as bcrypt from 'bcrypt';
@Injectable()
export class AuthService {
constructor(
@InjectRepository(User)
private userRepository: Repository<User>,
) {}
async signUp(authDto: AuthDto): Promise<void> {
const { username, password } = authDto;
const user = new User();
user.username = username;
user.password = await bcrypt.hash(password, 10);
await user.save();
}
async validateUser(username: string, password: string): Promise<User> {
const user = await this.userRepository.findOne({ where: { username } });
if (!user || !(await bcrypt.compare(password, user.password))) {
throw new UnauthorizedException('Invalid username or password');
}
return user;
}
}
```
5. 创建本地策略
在 `src/auth` 目录下创建 `local.strategy.ts` 文件,并定义本地策略,例如:
```typescript
import { Injectable } 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 authService: AuthService) {
super();
}
async validate(username: string, password: string): Promise<any> {
const user = await this.authService.validateUser(username, password);
return user;
}
}
```
6. 创建认证模块
在 `src/auth` 目录下创建 `auth.module.ts` 文件,并定义认证模块,例如:
```typescript
import { Module } from '@nestjs/common';
import { PassportModule } from '@nestjs/passport';
import { TypeOrmModule } from '@nestjs/typeorm';
import { AuthService } from './auth.service';
import { LocalStrategy } from './local.strategy';
import { UserController } from './user.controller';
import { User } from './user.entity';
@Module({
imports: [TypeOrmModule.forFeature([User]), PassportModule],
providers: [AuthService, LocalStrategy],
controllers: [UserController],
})
export class AuthModule {}
```
7. 创建用户控制器
在 `src/auth` 目录下创建 `user.controller.ts` 文件,并定义用户控制器,例如:
```typescript
import { Body, Controller, Post } from '@nestjs/common';
import { AuthService } from './auth.service';
import { AuthDto } from './dto/auth.dto';
@Controller('users')
export class UserController {
constructor(private authService: AuthService) {}
@Post('signup')
async signUp(@Body() authDto: AuthDto): Promise<void> {
await this.authService.signUp(authDto);
}
}
```
8. 配置认证路由
在 `src/app.module.ts` 文件中配置认证路由,例如:
```typescript
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { AuthModule } from './auth/auth.module';
import { User } from './auth/user.entity';
@Module({
imports: [
TypeOrmModule.forRoot({
type: 'sqlite',
database: 'database.sqlite',
entities: [User],
synchronize: true,
}),
AuthModule,
],
})
export class AppModule {}
```
9. 配置认证守卫
在需要进行认证的路由上配置认证守卫,例如:
```typescript
import { Controller, Get, UseGuards } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
@Controller('cats')
export class CatsController {
@Get()
@UseGuards(AuthGuard('local'))
findAll() {
// 仅经过认证的用户才能访问该路由
}
}
```
以上就是 NestJS 实现用户注册、验证和登录功能的步骤。希望对你有所帮助!
阅读全文