Nestjs构建Certeasy证书自动化平台 - 业务实现(登录注册)

118 阅读2分钟

jwt+typeorm.jpg

摘要

作为一个业务系统,用户的登录和注册是必不可少的,因此在开始本章节之前,请先阅读用户模块相关功能【 业务实现(用户模块)

业务关键JWT

引入JWT

$ npm install --save @nestjs/jwt

模块实现

1.初始化jwt

app.module.ts主模块引入jwt.module,使用 registerAsync inject 注入 ConfigService 读取配置数据

JwtModule.registerAsync({
  global: true,
  imports: [ConfigModule],
  inject: [ConfigService],
  useFactory: async (configService: ConfigService) => ({
    secret: configService.get<string>('jwt.secret_key', 'wC4YmUW1KpBazWUy'),
    signOptions: {
      algorithm: 'HS256',
      expiresIn: '24h',
    },
  }),
}),

2.创建模块

使用 NestJS CLI命令初始化模块,构建控制器及服务

nest g mo modules/auth

image.png

  • 创建 Controller
nest g co modules/auth --no-spec

image.png

  • 创建 Service
nest g s modules/auth --no-spec

image.png

image.png

3.注册

  @Post('signup')
  @Public()
  @ApiOperation({
    summary: '注册接口',
  })
  @ApiResponse({
    status: HttpStatus.OK,
    type: SwaggerBaseApiResponse(EmptyResponseType),
  })
  @ApiResponse({
    status: HttpStatus.BAD_REQUEST,
    type: BaseApiErrorResponse,
  })
  @HttpCode(HttpStatus.OK)
  async signup(@Body() data: SignupDto) {
    return await this.authService.signup(data);
  }

4.登录

  @Post('signin')
  @Public()
  @ApiOperation({
    summary: '登录接口',
  })
  @ApiResponse({
    status: HttpStatus.OK,
    type: SwaggerBaseApiResponse(SigninOutputDto),
  })
  @ApiResponse({
    status: HttpStatus.BAD_REQUEST,
    type: BaseApiErrorResponse,
  })
  @HttpCode(HttpStatus.OK)
  async signin(@Body() data: SigninDto): Promise<SigninOutputDto> {
    return await this.authService.signin(data);
  }

image.png

5.其他功能

更多代码请查看 certeasy_nest_open/src/modules/auth at main · CerteasyTeam/certeasy_nest_open (github.com)

系列文章

开源

联系

wechat: zuxcloud

Email: zuxing.xu@lettered.cn