SysLoginController.java 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. package com.ruoyi.web.controller.system;
  2. import javax.servlet.http.HttpServletRequest;
  3. import javax.servlet.http.HttpServletResponse;
  4. import com.ruoyi.common.constant.Constants;
  5. import com.ruoyi.common.core.domain.entity.SysUser;
  6. import com.ruoyi.framework.manager.AsyncManager;
  7. import com.ruoyi.framework.manager.factory.AsyncFactory;
  8. import com.ruoyi.framework.shiro.service.SysLoginService;
  9. import com.ruoyi.framework.shiro.util.SMSUtils;
  10. import com.ruoyi.system.service.ISysLogininforService;
  11. import com.ruoyi.system.service.ISysUserService;
  12. import org.apache.shiro.SecurityUtils;
  13. import org.apache.shiro.authc.AuthenticationException;
  14. import org.apache.shiro.authc.UsernamePasswordToken;
  15. import org.apache.shiro.subject.Subject;
  16. import org.springframework.beans.factory.annotation.Autowired;
  17. import org.springframework.beans.factory.annotation.Value;
  18. import org.springframework.stereotype.Controller;
  19. import org.springframework.ui.ModelMap;
  20. import org.springframework.web.bind.annotation.GetMapping;
  21. import org.springframework.web.bind.annotation.PostMapping;
  22. import org.springframework.web.bind.annotation.ResponseBody;
  23. import com.ruoyi.common.core.controller.BaseController;
  24. import com.ruoyi.common.core.domain.AjaxResult;
  25. import com.ruoyi.common.core.text.Convert;
  26. import com.ruoyi.common.utils.ServletUtils;
  27. import com.ruoyi.common.utils.StringUtils;
  28. import com.ruoyi.framework.web.service.ConfigService;
  29. import java.io.IOException;
  30. import java.security.NoSuchAlgorithmException;
  31. /**
  32. * 登录验证
  33. *
  34. * @author ruoyi
  35. */
  36. @Controller
  37. public class SysLoginController extends BaseController
  38. {
  39. /**
  40. * 是否开启记住我功能
  41. */
  42. @Value("${shiro.rememberMe.enabled: false}")
  43. private boolean rememberMe;
  44. @Autowired
  45. private ConfigService configService;
  46. @Autowired
  47. private ISysUserService userService;
  48. @Autowired
  49. private SysLoginService loginService;
  50. @Autowired
  51. private SMSUtils smsUtils;
  52. @GetMapping("/login")
  53. public String login(HttpServletRequest request, HttpServletResponse response, ModelMap mmap)
  54. {
  55. // 如果是Ajax请求,返回Json字符串。
  56. if (ServletUtils.isAjaxRequest(request))
  57. {
  58. return ServletUtils.renderString(response, "{\"code\":\"1\",\"msg\":\"未登录或登录超时。请重新登录\"}");
  59. }
  60. // 是否开启记住我
  61. mmap.put("isRemembered", rememberMe);
  62. // 是否开启用户注册
  63. mmap.put("isAllowRegister", Convert.toBool(configService.getKey("sys.account.registerUser"), false));
  64. // 是否开启短信验证码登录
  65. mmap.put("smsLoginEnabled", Convert.toBool(configService.getKey("sys.account.smsLoginEnabled"), false));
  66. // 是否开启短信验证码前的图形验证码
  67. mmap.put("smsCaptchaEnabled", Convert.toBool(configService.getKey("sys.account.smsCaptchaEnabled"), true));
  68. return "login";
  69. }
  70. /* @PostMapping("/login")
  71. @ResponseBody
  72. public AjaxResult ajaxLogin(String username, String password, Boolean rememberMe)
  73. {
  74. UsernamePasswordToken token = new UsernamePasswordToken(username, password, rememberMe);
  75. Subject subject = SecurityUtils.getSubject();
  76. try
  77. {
  78. subject.login(token);
  79. return success();
  80. }
  81. catch (AuthenticationException e)
  82. {
  83. String msg = "用户或密码错误";
  84. if (StringUtils.isNotEmpty(e.getMessage()))
  85. {
  86. msg = e.getMessage();
  87. }
  88. return error(msg);
  89. }
  90. }*/
  91. /**
  92. * 发送短信验证码
  93. */
  94. @PostMapping("/sendSmsCode")
  95. @ResponseBody
  96. public AjaxResult sendSmsCode(String phone, String captchaCode)
  97. {
  98. try
  99. {
  100. // 获取图形验证码开关配置
  101. boolean smsCaptchaEnabled = Convert.toBool(configService.getKey("sys.account.smsCaptchaEnabled"), true);
  102. // 如果开启了图形验证码,验证图形验证码
  103. if (smsCaptchaEnabled) {
  104. if (StringUtils.isEmpty(captchaCode)) {
  105. return error("请输入图形验证码");
  106. }
  107. // 验证图形验证码是否正确
  108. if (!validateCaptcha(captchaCode)) {
  109. return error("图形验证码错误");
  110. }
  111. }
  112. // 手机号格式验证
  113. if (StringUtils.isEmpty(phone)) {
  114. return error("请输入手机号码");
  115. }
  116. if (!phone.matches("^1[3-9]\\d{9}$")) {
  117. return error("请输入正确的手机号码");
  118. }
  119. // 检查手机号是否已注册
  120. SysUser user = userService.selectUserByPhoneNumber(phone);
  121. if (user == null) {
  122. return error("该手机号未注册");
  123. }
  124. // 检查发送频率(防止频繁发送)- 60秒内只能发送一次
  125. HttpServletRequest request = ServletUtils.getRequest();
  126. Long lastSendTime = (Long) request.getSession().getAttribute("sms_last_send_time_" + phone);
  127. if (lastSendTime != null && System.currentTimeMillis() - lastSendTime < 60000) {
  128. long waitTime = 60 - (System.currentTimeMillis() - lastSendTime) / 1000;
  129. return error("请求过于频繁,请" + waitTime + "秒后再试");
  130. }
  131. // 生成验证码
  132. String smsCode = generateSmsCode();
  133. // 存储验证码到Session(有效期5分钟)
  134. request.getSession().setAttribute("sms_code_" + phone, smsCode);
  135. request.getSession().setAttribute("sms_code_time_" + phone, System.currentTimeMillis());
  136. request.getSession().setAttribute("sms_last_send_time_" + phone, System.currentTimeMillis());
  137. // 调用短信服务发送验证码
  138. boolean sendResult = sendSms(phone, smsCode);
  139. // boolean sendResult = true;
  140. if (sendResult)
  141. {
  142. System.out.println(smsCode);
  143. // 记录发送日志,不需要记录日志
  144. //AsyncManager.me().execute(AsyncFactory.recordLogininfor(phone, Constants.LOGIN_SUCCESS, "短信验证码发送成功"));
  145. return success("验证码发送成功");
  146. }
  147. else
  148. {
  149. return error("验证码发送失败,请稍后重试");
  150. }
  151. }
  152. catch (Exception e)
  153. {
  154. return error("验证码发送失败,请稍后重试");
  155. }
  156. }
  157. /**
  158. * 短信验证码登录
  159. */
  160. @PostMapping("/smsLogin")
  161. @ResponseBody
  162. public AjaxResult smsLogin(String phone, String smsCode, Boolean rememberMe)
  163. {
  164. try
  165. {
  166. // 验证短信验证码并获取用户
  167. SysUser user = loginService.smsLogin(phone, smsCode);
  168. // 使用固定密码和用户名进行Shiro登录
  169. UsernamePasswordToken token = new UsernamePasswordToken(user.getLoginName(), "SMS_LOGIN_FIXED_PASSWORD_2025", rememberMe);
  170. Subject subject = SecurityUtils.getSubject();
  171. subject.login(token);
  172. return success();
  173. }
  174. catch (Exception e)
  175. {
  176. // 直接返回具体的错误信息
  177. return error(e.getMessage());
  178. }
  179. }
  180. private String generateSmsCode() {
  181. // 生成6位随机数字
  182. return String.valueOf((int) ((Math.random() * 9 + 1) * 100000));
  183. }
  184. private boolean sendSms(String phone, String smsCode) {
  185. // 实现短信发送逻辑
  186. // 这里需要集成实际的短信服务商
  187. boolean b = false;
  188. try {
  189. b = smsUtils.sendMsg(phone, smsCode);
  190. } catch (IOException e) {
  191. e.printStackTrace();
  192. } catch (NoSuchAlgorithmException e) {
  193. e.printStackTrace();
  194. }
  195. return b;
  196. }
  197. /**
  198. * 验证图形验证码
  199. */
  200. private boolean validateCaptcha(String captchaCode) {
  201. try {
  202. HttpServletRequest request = ServletUtils.getRequest();
  203. // 调试:打印Session中所有与验证码相关的属性
  204. java.util.Enumeration<String> attributeNames = request.getSession().getAttributeNames();
  205. while (attributeNames.hasMoreElements()) {
  206. String name = attributeNames.nextElement();
  207. if (name.toLowerCase().contains("captcha") || name.toLowerCase().contains("kaptcha")) {
  208. Object value = request.getSession().getAttribute(name);
  209. }
  210. }
  211. // 尝试常见的验证码Session key
  212. String[] possibleKeys = {
  213. "KAPTCHA_SESSION_KEY",
  214. "kaptchaCode",
  215. com.ruoyi.common.constant.ShiroConstants.CURRENT_CAPTCHA,
  216. "captcha",
  217. "verifyCode"
  218. };
  219. String sessionCaptcha = null;
  220. String usedKey = null;
  221. for (String key : possibleKeys) {
  222. Object value = request.getSession().getAttribute(key);
  223. if (value != null) {
  224. sessionCaptcha = value.toString();
  225. usedKey = key;
  226. break;
  227. }
  228. }
  229. if (StringUtils.isEmpty(sessionCaptcha)) {
  230. return false;
  231. }
  232. // 验证码比较(忽略大小写)
  233. boolean isValid = sessionCaptcha.equalsIgnoreCase(captchaCode);
  234. // 验证后清除Session中的验证码,防止重复使用
  235. if (isValid && usedKey != null) {
  236. request.getSession().removeAttribute(usedKey);
  237. }
  238. return isValid;
  239. } catch (Exception e) {
  240. return false;
  241. }
  242. }
  243. @GetMapping("/unauth")
  244. public String unauth()
  245. {
  246. return "error/unauth";
  247. }
  248. }