package com.ruoyi.web.controller.system; 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> 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.setNickName(appletUserDecodeData.getPhoneNumber().replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2")); 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 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 roles = permissionService.getRolePermission(user); // 权限集合 Set 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 menus = menuService.selectMenuTreeByUserId(userId); return AjaxResult.success(menuService.buildMenus(menus)); } }