nestjs 管道验证DTO

本文介绍了如何在NestJS应用中使用DTO(DataTransferObject)和TypeStack的class-validator/class-transformer库进行用户登录验证,包括创建验证DTO文件、在控制器中使用验证管道、全局配置验证和处理验证异常。
摘要由CSDN通过智能技术生成

我将dto文件全收集到一个dto文件夹里,可按照文档建议。

1.安装依赖

pnpm i --save class-validator class-transformer

参考文档
https://github.com/typestack/class-transformericon-default.png?t=N7T8https://github.com/typestack/class-transformer

https://github.com/typestack/class-validatoricon-default.png?t=N7T8https://github.com/typestack/class-validator2. 新建一个用户登录的验证dto文件

src/dto/login-manage.dto

import { IsNotEmpty, IsString, Length } from "class-validator"

/**
 * 管理员登录
 * 加入验证管道pipe
 */
export class LoginManageDto {

    @IsString()
    @IsNotEmpty({ message: '管理员不能为空' })
    username: string

    @IsString()
    @IsNotEmpty({ message: '密码不能为空' })
    @Length(6, 16, {
        message: '密码长度必须在6-16位之间'
    })
    password: string
}

3.在controller文件中加入该管道dto文件

import { Body, Controller, Post } from '@nestjs/common';
import { AuthService } from './auth.service';
import { LoginManageDto } from 'src/dto/login-manage.dto';

/**
 * 用户鉴权
 */

@Controller('admin/auth')
export class AuthController {

    constructor(
        private authService: AuthService,
    ) {}

    /**
     * 登录
     * 可在@Body()引入内置管道pipe
     */
    @Post('/login')
    async login(@Body() dto: LoginManageDto) {
        const { username, password } = dto;

        let token = await this.authService.manageLogin(username, password);

        //登录成功 返回token值
        return {
            token
        }
    }
    
}

4.在main.ts中加入全局管道

//全局配置管道pipe拦截器
  app.useGlobalPipes(new ValidationPipe({
    //去除在类上不存在的字段
    //whitelist: true
  }));

5.在filter拦截器中,验证异常返回的是status: 400

6. 这样做比较简单,不用想太复杂,也可以用内置管道

@Get('/find')
    async getManage(@Query('id', ParseIntPipe) id: number) {
        console.log(typeof id)
        
    }

 7. 唯一差别是我文件是使用filter做了全局拦截的。

  • 4
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,关于 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 实现用户注册、验证和登录功能的步骤。希望对你有所帮助!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值