xiangpei
2025-04-18 ccadf9480d4e6a9dcc227a2a0b1f9ae0612e36fd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package com.monkeylessey.controller.system;
 
import com.google.code.kaptcha.Producer;
import com.monkeylessey.constant.RedisKeyExpireConstants;
import com.monkeylessey.constant.RedisKeyPrefixConstants;
import com.monkeylessey.sys.domain.vo.CaptchaVO;
import com.monkeylessey.response.Result;
import com.monkeylessey.framework.utils.RedisUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
 
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.UUID;
 
/**
 * @author 29443
 * @version 1.0
 * @date 2022/4/21
 */
@RestController
@RequiredArgsConstructor
@Api(value = "登录相关", tags = "登录相关")
public class SysLoginController {
 
    private final RedisUtil redisUtil;
    private final Producer captcha;
 
 
    @GetMapping("/captcha")
    @ApiOperation(value = "获取验证码", notes = "获取验证码")
    public Result getCaptcha() throws IOException {
        // 生成验证码id
        String captchaId = UUID.randomUUID().toString().substring(0, 10);
        String key = RedisKeyPrefixConstants.CAPTCHA + captchaId;
 
        // 生成验证码
        String code = captcha.createText();
        BufferedImage image = captcha.createImage(code);
 
        // 创建字节数组缓冲
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
 
        // 将生成的验证码BufferedImage转为byte数组
        ImageIO.write(image, "jpg", byteArrayOutputStream);
        byte[] bytes = byteArrayOutputStream.toByteArray();
 
        // 将byte数组使用Base64编码
        String base64 = Base64Utils.encodeToString(bytes);
 
        // 将生成的验证码放入redis,默认有效2分钟
        redisUtil.saveForValueWithExpire(key, code, RedisKeyExpireConstants.CAPTCHA_EXPIRE_TIME, RedisKeyExpireConstants.CAPTCHA_TIME_UNIT);
        return Result.ok("获取验证码成功").data(new CaptchaVO(captchaId, "data:image/jpg;base64," + base64));
    }
}