Skip to content

登录注册

安装包

向军大叔每晚八点在 抖音bilibli 直播

xj-small

我们通过一个用户注册与登录来演示加密的使用,首先安装 argon2 扩展包对密码进行加密。

pnpm add argon2

然后创建资源

nest g res auth

用户注册

修改create-auth.dto.ts对字段进行验证

import { IsEmail, IsNotEmpty } from 'class-validator';

export class CreateAuthDto {
  @IsNotEmpty({ message: '用户名不能为空' })
  @IsEmail({}, { message: '用户名必须是邮箱' })
  email: string;
  @IsNotEmpty({ message: '密码不能为空' })
  password: string;
}

然后修改 auth.service.ts 完善业务

import { PrismaClient } from '@prisma/client';
import { Injectable } from '@nestjs/common';
import { CreateAuthDto } from './dto/create-auth.dto';
import { UpdateAuthDto } from './dto/update-auth.dto';
import * as argon2 from 'argon2';

@Injectable()
export class AuthService extends PrismaClient {
  async register(createAuthDto: CreateAuthDto) {
  	//加密用户密码
    const password = await argon2.hash(createAuthDto.password);
    const user = await this.users.create({
      data: {
        email: createAuthDto.email,
        password,
      },
    });
    
    //返回的数据不显示密码
    delete user.password;
    return user;
  }
  ...
}

然后控制器auth.controller.ts中使用

@Controller()
export class AuthController {
  constructor(private readonly authService: AuthService) {}

  @Post('register')
  register(@Body() createAuthDto: CreateAuthDto) {
    return this.authService.register(createAuthDto);
  }
  ...
}

接下来在postman中请求 register 查看效果吧

用户登录

创建 login-dto.ts 内容如下。

  • 其中 IsExist 自定义的验证,请查看管道章节,你也可以把这行删除
import { IsEmail, IsNotEmpty } from 'class-validator';
import { IsExist } from 'src/rules/is-exist.rule';

export class LoginDto {
  @IsNotEmpty({ message: '用户名不能为空' })
  @IsEmail({}, { message: '用户名必须是邮箱' })
  @IsExist({ field: 'email', table: 'users' }, { message: '用户不存在' })
  email: string;
  @IsNotEmpty({ message: '密码不能为空' })
  password: string;
}

修改 auth.service.ts,添加login方法

import { PrismaClient } from '@prisma/client';
import { Injectable, BadRequestException } from '@nestjs/common';
import { CreateAuthDto } from './dto/create-auth.dto';
import * as argon2 from 'argon2';

@Injectable()
export class AuthService extends PrismaClient {
  ...
  async login({ email, password }: CreateAuthDto) {
    const user = await this.users.findUnique({
      where: { email },
    });
    if (!user) throw new BadRequestException('用户不存在');

    const psMatch = await argon2.verify(user.password, password);

    if (!psMatch) throw new BadRequestException('密码输入错误');

    delete user.password;
    return user;
  }
}

控制器代码

@Controller()
export class AuthController {
  constructor(private readonly authService: AuthService) {}
  ...
  @Post('login')
  login(@Body() data: LoginDto) {
    return this.authService.login(data);
  }
}

现在使用postman测试login 接口吧