liujie
2025-12-26 e4e872b1e5c20a232222380e6a49b648a6672b4b
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
package com.ruoyi.web.controller.system;
 
import cn.hutool.core.util.PhoneUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.entity.SysMenu;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.entity.TAppUserResp;
import com.ruoyi.common.core.domain.model.LoginAppBody;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.common.core.domain.model.LoginUserApplet;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.redis.service.RedisService;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.framework.web.service.SysPermissionService;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.model.TAppUser;
import com.ruoyi.system.service.ISysMenuService;
import com.ruoyi.system.service.ISysRoleService;
import com.ruoyi.system.service.TAppUserService;
import com.ruoyi.system.utils.wx.body.resp.Code2SessionRespBody;
import com.ruoyi.system.utils.wx.body.resq.Code2SessionResqBody;
import com.ruoyi.system.utils.wx.model.WeixinProperties;
import com.ruoyi.system.utils.wx.pojo.AppletUserDecodeData;
import com.ruoyi.system.utils.wx.pojo.AppletUserEncrypteData;
import com.ruoyi.system.utils.wx.tools.WxAppletTools;
import com.ruoyi.system.utils.wx.tools.WxUtils;
import com.ruoyi.web.controller.tool.MsgUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
 
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
 
/**
 * 登录验证
 *
 * @author ruoyi
 */
@Slf4j
@Api(tags = "登录")
@RestController
public class SysLoginController
{
    @Autowired
    private SysLoginService loginService;
 
    @Autowired
    private ISysMenuService menuService;
 
    @Autowired
    private SysPermissionService permissionService;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private ISysRoleService roleService;
    @Autowired
    private MsgUtils msgUtils;
    @Autowired
    private RestTemplate wxRestTemplate;
    @Autowired
    private WeixinProperties wxConfig;
    @Autowired
    private RedisService redisService;
    @Autowired
    private TAppUserService appUserService;
 
    /**
     * 手机号正则表达式(11位数字,以1开头)
     */
    private static final Pattern PHONE_PATTERN = Pattern.compile("^1[3-9]\\d{9}$");
 
    /**
     * Redis Key 前缀
     */
    private static final String SMS_LIMIT_PHONE_KEY = "sms_limit:phone:";
    private static final String SMS_LIMIT_PHONE_DAILY_KEY = "sms_limit:phone_daily:";
    private static final String SMS_LIMIT_IP_KEY = "sms_limit:ip:";
    private static final String SMS_LIMIT_IP_HOURLY_KEY = "sms_limit:ip_hourly:";
 
    /**
     * 限制参数
     */
    private static final int PHONE_LIMIT_SECONDS = 60;           // 手机号60秒限制
    private static final int PHONE_DAILY_LIMIT = 10;             // 手机号每日最多10次
    private static final int PHONE_DAILY_EXPIRE_HOURS = 24;      // 手机号每日限制过期时间
    private static final int IP_LIMIT_PER_MINUTE = 5;            // IP每分钟最多5次
    private static final int IP_LIMIT_PER_HOUR = 20;             // IP每小时最多20次
 
    /**
     * 获取验证码
     *
     * @param phone 手机号
     * @return 结果
     */
    @ApiOperation(value = "获取验证码",notes = "获取验证码")
    @GetMapping("/getCode")
    public AjaxResult getCode(@RequestParam String phone)
    {
        // 1. 校验手机号格式
        if (!StringUtils.hasLength(phone) || !PHONE_PATTERN.matcher(phone).matches()) {
            return AjaxResult.error(500, "手机号格式不正确");
        }
 
        // 2. 获取客户端IP
        String clientIp = IpUtils.getIpAddr();
 
        // 3. 检查手机号60秒限制
        String phoneKey = SMS_LIMIT_PHONE_KEY + phone;
        if (redisCache.hasKey(phoneKey)) {
            Long ttl = redisCache.getExpire(phoneKey);
            return AjaxResult.error(500, "请求过于频繁,请" + ttl + "秒后再试");
        }
 
        // 4. 检查手机号24小时限制
        String phoneDailyKey = SMS_LIMIT_PHONE_DAILY_KEY + phone;
        Integer phoneDailyCount = redisCache.getCacheObject(phoneDailyKey);
        if (phoneDailyCount != null && phoneDailyCount >= PHONE_DAILY_LIMIT) {
            return AjaxResult.error(500, "该手机号今日获取验证码次数已达上限");
        }
 
        // 5. 检查IP每分钟限制
        String ipKey = SMS_LIMIT_IP_KEY + clientIp;
        Integer ipCount = redisCache.getCacheObject(ipKey);
        if (ipCount != null && ipCount >= IP_LIMIT_PER_MINUTE) {
            return AjaxResult.error(500, "请求过于频繁,请稍后再试");
        }
 
        // 6. 检查IP每小时限制
        String ipHourlyKey = SMS_LIMIT_IP_HOURLY_KEY + clientIp;
        Integer ipHourlyCount = redisCache.getCacheObject(ipHourlyKey);
        if (ipHourlyCount != null && ipHourlyCount >= IP_LIMIT_PER_HOUR) {
            return AjaxResult.error(500, "请求次数过多,请1小时后再试");
        }
 
        // 7. 生成并发送验证码
        String code = String.valueOf((int) (Math.random() * 900000) + 100000);
        redisCache.setCacheObject(phone, code, 5 * 60, TimeUnit.SECONDS);
        try {
            msgUtils.sendMsg(phone, code);
        } catch (Exception e) {
            log.error("发送短信验证码失败,手机号:{},错误:{}", phone, e.getMessage());
            return AjaxResult.error(500, "发送短信验证码失败,请稍后重试");
        }
 
        // 8. 更新限制计数器
        // 手机号60秒限制
        redisCache.setCacheObject(phoneKey, 1, PHONE_LIMIT_SECONDS, TimeUnit.SECONDS);
 
        // 手机号每日限制
        if (phoneDailyCount == null) {
            redisCache.setCacheObject(phoneDailyKey, 1, PHONE_DAILY_EXPIRE_HOURS, TimeUnit.HOURS);
        } else {
            redisCache.setCacheObject(phoneDailyKey, phoneDailyCount + 1, PHONE_DAILY_EXPIRE_HOURS, TimeUnit.HOURS);
        }
 
        // IP每分钟限制
        if (ipCount == null) {
            redisCache.setCacheObject(ipKey, 1, 1, TimeUnit.MINUTES);
        } else {
            // 保持原有过期时间
            Long ipTtl = redisCache.getExpire(ipKey);
            redisCache.setCacheObject(ipKey, ipCount + 1, ipTtl.intValue() > 0 ? ipTtl.intValue() : 60, TimeUnit.SECONDS);
        }
 
        // IP每小时限制
        if (ipHourlyCount == null) {
            redisCache.setCacheObject(ipHourlyKey, 1, 1, TimeUnit.HOURS);
        } else {
            // 保持原有过期时间
            Long ipHourlyTtl = redisCache.getExpire(ipHourlyKey);
            redisCache.setCacheObject(ipHourlyKey, ipHourlyCount + 1, ipHourlyTtl.intValue() > 0 ? ipHourlyTtl.intValue() : 3600, TimeUnit.SECONDS);
        }
 
        log.info("验证码发送成功,手机号:{},IP:{}", phone, clientIp);
        return AjaxResult.success("发送短信验证码成功!5分钟内有效");
    }
 
    /**
     * 账号密码登录
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @ApiOperation(value = "短信登录",notes = "短信登录")
    @PostMapping("/loginCode")
    public AjaxResult loginCode(@RequestBody LoginBody loginBody)
    {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        LoginUserApplet loginUser = loginService.loginCodeApplet(loginBody.getUsername(), loginBody.getCode());
        ajax.put(Constants.TOKEN, tokenService.createTokenApplet(loginUser));
        ajax.put("info",loginUser);
        return ajax;
    }
 
    /**
     * 账号密码登录
     * 
     * @param param 登录信息
     * @return 结果
     */
    @ApiOperation(value = "账号密码登录",notes = "账号密码登录")
    @PostMapping("/loginApp")
    public AjaxResult login(@RequestBody String param)
    {
        LoginAppBody loginAppBody = JSON.parseObject(param, LoginAppBody.class);
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        LoginUserApplet loginUser = loginService.loginPwdApplet(loginAppBody.getAccount(), loginAppBody.getPassword());
        ajax.put(Constants.TOKEN, tokenService.createTokenApplet(loginUser));
        ajax.put("data",loginUser);
        return ajax;
    }
 
    @ApiOperation(value = "通过code获得openid,获取用户信息")
    @PostMapping("/openIdByJsCode")
    public R<Map<String, Object>> openIdByJsCode(@RequestBody AppletUserEncrypteData data) {
        log.info("<<<<<<<<换取openid开始<<<<<<<<:{}", data.getCode());
        WxAppletTools appletTools = new WxAppletTools(wxRestTemplate, wxConfig, redisService);
        Code2SessionRespBody body = appletTools.getOpenIdByJscode2session(new Code2SessionResqBody().build(data.getCode()));
        String openid = body.getOpenid();
        String sessionKey = body.getSessionKey();
        // 用户信息解密 数据验签
       if (StringUtils.hasLength(data.getSignature())) {
           WxUtils.verifySignature(data.getRawData(), sessionKey, data.getSignature());
       }
       if(StringUtils.isEmpty(data.getEncryptedData()) || StringUtils.isEmpty(data.getIv())){
           return R.fail("已拒绝授权");
       }
       AppletUserDecodeData appletUserDecodeData = WxUtils.encryptedData(data.getEncryptedData(), sessionKey,  data.getIv());
       appletUserDecodeData.setOpenId(openid);
        // 先使用openId和当前手机号进行查询
        TAppUser sysAppUser = appUserService.getOne(Wrappers.lambdaQuery(TAppUser.class)
                .and(e->e.eq(TAppUser::getOpenid, openid)));
        if (sysAppUser==null){
            sysAppUser = new TAppUser();
           sysAppUser.setPhone(appletUserDecodeData.getPhoneNumber());
            sysAppUser.setOpenid(openid);
            // 手机号中间四位替换为*
            sysAppUser.setName("用户" + PhoneUtil.subAfter(appletUserDecodeData.getPhoneNumber()).toString());
            sysAppUser.setProfilePhoto("https://jiashikang.cn/images/2025-12-26/30ae8143-dc90-49b7-bc1f-ac49b74ae092.png");
            appUserService.save(sysAppUser);
        }else {
            // 判断账号是否被冻结
            if (sysAppUser.getStatus() == 2){
                return R.fail("账号已冻结,请联系管理员");
            }
            // 手机号相同但openId为空的情况
            sysAppUser.setOpenid(openid);
            sysAppUser.setPhone(appletUserDecodeData.getPhoneNumber());
            appUserService.updateById(sysAppUser);
        }
        LoginUserApplet loginUserApplet = new LoginUserApplet();
        TAppUserResp sysUserResp = new TAppUserResp();
        BeanUtils.copyProperties(sysAppUser, sysUserResp);
        loginUserApplet.setUser(sysUserResp);
        loginUserApplet.setUserId(sysAppUser.getId());
        Map<String, Object> tokenInfos = new HashMap<>();
        tokenInfos.put("token",tokenService.createTokenApplet(loginUserApplet));
        tokenInfos.put("info",loginUserApplet);
        return R.ok(tokenInfos);
    }
 
 
    /**
     * 获取用户信息
     * 
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public AjaxResult getInfo()
    {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ajax;
    }
 
    /**
     * 获取路由信息
     * 
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public AjaxResult getRouters()
    {
        Long userId = SecurityUtils.getUserId();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
        return AjaxResult.success(menuService.buildMenus(menus));
    }
}