|
1 | | -import { Body, Controller, Get, Post, Query } from '@nestjs/common'; |
| 1 | +import { Body, Controller, Get, Post, Query, Res, Session } from '@nestjs/common'; |
2 | 2 | import { LoginDto } from './dto/login.dto'; |
3 | 3 | import { LoginService } from './login.service'; |
4 | 4 | import { LoginVo } from './vo/login.vo'; |
5 | | - |
| 5 | +import * as svgCaptcha from 'svg-captcha'; |
| 6 | +import { HttpException } from '@nestjs/common/exceptions'; |
| 7 | +import { HttpStatus } from '@nestjs/common/enums'; |
6 | 8 | @Controller() |
7 | 9 | export class LoginController { |
8 | 10 | constructor(private readonly loginService: LoginService) {} |
9 | 11 |
|
10 | 12 | @Post('login') |
11 | | - async loginApi(@Body() req: LoginDto): Promise<LoginVo> { |
12 | | - return await this.loginService.loginApi(req); |
| 13 | + async loginApi(@Body() req: LoginDto, @Session() session: any): Promise<LoginVo> { |
| 14 | + const storedCaptcha = session.code; |
| 15 | + if (req.captcha && storedCaptcha && req.captcha.toLowerCase() === storedCaptcha.toLowerCase()) { |
| 16 | + return await this.loginService.loginApi(req); |
| 17 | + } else { |
| 18 | + throw new HttpException('验证码错误', HttpStatus.OK); |
| 19 | + } |
13 | 20 | } |
14 | 21 |
|
15 | 22 | @Get('refresh') |
16 | 23 | async refreshTokenApi(@Query('token') token: string): Promise<LoginVo> { |
17 | 24 | return await this.loginService.refreshTokenApi(token); |
18 | 25 | } |
| 26 | + |
| 27 | + @Get('captcha') |
| 28 | + getCaptchaApi(@Res() res: any, @Session() session: any) { |
| 29 | + const captcha = svgCaptcha.create({ |
| 30 | + size: 4, //生成几个验证码 |
| 31 | + fontSize: 50, //文字大小 |
| 32 | + width: 100, //宽度 |
| 33 | + height: 34, //高度 |
| 34 | + background: '#cc9966', //背景颜色 |
| 35 | + }); |
| 36 | + console.log(captcha, '??'); |
| 37 | + session['code'] = captcha['text']; //存储验证码记录到session |
| 38 | + res.set('Content-Type', 'image/svg+xml'); |
| 39 | + res.send(captcha['data']); |
| 40 | + } |
19 | 41 | } |
0 commit comments