xyc
1 天以前 079d872fabfe488abf485d8898c40ff1fd746472
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
package com.trafficaudit.security.captcha;
 
import com.trafficaudit.common.Result;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
 
import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.Map;
 
@RestController
@RequestMapping("/api/auth")
public class CaptchaController {
 
    @Resource
    private CaptchaService captchaService;
 
    @GetMapping("/captcha")
    public Result<Map<String, Object>> captcha() {
        return Result.ok(captchaService.generate());
    }
 
    @PostMapping("/captcha/verify")
    public Result<Map<String, Object>> verify(@RequestBody Map<String, Object> params) {
        String captchaId = (String) params.get("captchaId");
        List<String> clickIds = strList(params.get("captchaClickIds"));
        CaptchaService.VerifyResult r = captchaService.verify(captchaId, clickIds);
        switch (r) {
            case OK:
                return Result.ok(Collections.singletonMap("ok", true));
            case WRONG:
                return Result.error(4001, "点击顺序错误,请重新点击");
            case RETRY_LIMIT:
                return Result.error(4002, "错误次数过多,已更换题目");
            default:
                return Result.error(4003, "验证码不存在或已过期,请刷新");
        }
    }
 
    @SuppressWarnings("unchecked")
    private List<String> strList(Object o) {
        if (o instanceof List) {
            return (List<String>) o;
        }
        return Collections.emptyList();
    }
}