SysLoginController.java 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  1. package com.ydtech.modules.admin.controller;
  2. import com.alibaba.fastjson.JSONObject;
  3. import com.google.code.kaptcha.Constants;
  4. import com.google.code.kaptcha.Producer;
  5. import com.ydtech.config.MasterPasswordConfig;
  6. import com.ydtech.config.WechatOpenProperties;
  7. import com.ydtech.exception.SystemException;
  8. import com.ydtech.modules.admin.model.SysMsgLog;
  9. import com.ydtech.modules.admin.model.SysUser;
  10. import com.ydtech.modules.admin.service.SysMsgLogService;
  11. import com.ydtech.modules.esm.model.EsmUserInternal;
  12. import com.ydtech.modules.esm.service.EsmUserInternalService;
  13. import com.ydtech.security.JwtAuthenticatioToken;
  14. import com.ydtech.security.utils.PasswordUtils;
  15. import com.ydtech.security.utils.SecurityUtils;
  16. import com.ydtech.modules.admin.service.SysUserService;
  17. import com.ydtech.modules.admin.vo.LoginBean;
  18. import com.ydtech.core.page.HttpResult;
  19. import com.ydtech.utils.IPUtil;
  20. import io.swagger.annotations.Api;
  21. import io.swagger.annotations.ApiOperation;
  22. import lombok.extern.slf4j.Slf4j;
  23. import me.chanjar.weixin.common.bean.oauth2.WxOAuth2AccessToken;
  24. import me.chanjar.weixin.common.error.WxErrorException;
  25. import me.chanjar.weixin.mp.api.WxMpService;
  26. import net.jodah.expiringmap.ExpirationPolicy;
  27. import net.jodah.expiringmap.ExpiringMap;
  28. import org.apache.tomcat.util.http.fileupload.IOUtils;
  29. import org.springframework.beans.factory.annotation.Autowired;
  30. import org.springframework.data.redis.core.StringRedisTemplate;
  31. import org.springframework.security.authentication.AuthenticationManager;
  32. import org.springframework.util.StringUtils;
  33. import org.springframework.web.bind.annotation.*;
  34. import javax.imageio.ImageIO;
  35. import javax.servlet.ServletException;
  36. import javax.servlet.ServletOutputStream;
  37. import javax.servlet.http.HttpServletRequest;
  38. import javax.servlet.http.HttpServletResponse;
  39. import java.awt.image.BufferedImage;
  40. import java.io.*;
  41. import java.net.HttpURLConnection;
  42. import java.net.URL;
  43. import java.net.URLEncoder;
  44. import java.util.*;
  45. import java.util.concurrent.TimeUnit;
  46. import static com.ydtech.constants.RedisConstant.PHONE_VERIFICATION_CODE_KEY;
  47. import static com.ydtech.constants.RedisConstant.PHONE_VERIFICATION_CODE_KEY_TIME;
  48. /**
  49. * 登录控制器
  50. *
  51. * @author Yasepix
  52. * @date Oct 29, 2018
  53. */
  54. @Slf4j
  55. @RestController
  56. @Api(tags = "登录控制器")
  57. public class SysLoginController {
  58. // https://wenku.baidu.com/view/d7b845cf49fe04a1b0717fd5360cba1aa9118c49.html
  59. private static final ExpiringMap<String, String> redis = ExpiringMap.builder()
  60. .maxSize(100)
  61. .expiration(20, TimeUnit.SECONDS)
  62. .variableExpiration().expirationPolicy(ExpirationPolicy.CREATED).build();
  63. @Autowired
  64. private Producer producer;
  65. @Autowired
  66. private SysUserService sysUserService;
  67. @Autowired
  68. private AuthenticationManager authenticationManager;
  69. @Autowired
  70. private SysMsgLogService sysMsgLogService;
  71. @Autowired
  72. private StringRedisTemplate stringRedisTemplate;
  73. @Autowired
  74. private EsmUserInternalService esmUserInternalService;
  75. @Autowired
  76. private MasterPasswordConfig masterPasswordConfig;
  77. @GetMapping("captcha.jpg")
  78. @ApiOperation(value = "获取验证码", produces = "application/octet-stream")
  79. public void captcha(HttpServletResponse response, HttpServletRequest request) throws ServletException, IOException {
  80. response.setHeader("Cache-Control", "no-store, no-cache");
  81. response.setContentType("image/jpeg");
  82. // 生成文字验证码
  83. String text = producer.createText();
  84. // 生成图片验证码
  85. BufferedImage image = producer.createImage(text);
  86. // 保存到验证码到 session
  87. request.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY, text);
  88. redis.put(IPUtil.getIpAddr(request), text, 120, TimeUnit.SECONDS);
  89. System.out.println("存入session验证码为:" + text);
  90. log.info("存入session验证码为:" + text);
  91. ServletOutputStream out = response.getOutputStream();
  92. ImageIO.write(image, "jpg", out);
  93. IOUtils.closeQuietly(out);
  94. }
  95. /**
  96. * 登录接口
  97. */
  98. @PostMapping(value = "/login")
  99. @ApiOperation(value = "登录")
  100. public HttpResult login(@RequestBody LoginBean loginBean, HttpServletRequest request) throws IOException {
  101. String username = loginBean.getAccount();
  102. String password = loginBean.getPassword();
  103. String captcha = loginBean.getCaptcha();
  104. // 从session中获取之前保存的验证码跟前台传来的验证码进行匹配
  105. Object kaptcha = request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
  106. System.out.println("页面验证码:" + captcha + "===" + "session验证码:" + kaptcha);
  107. log.info("页面验证码:" + captcha + "===" + "session验证码:" + kaptcha);
  108. if (kaptcha == null) {
  109. // 从redis中获取
  110. kaptcha = redis.get(IPUtil.getIpAddr(request));
  111. log.info("session获取失败,改为redis中获取!页面验证码:" + captcha + "===" + "redis验证码:" + kaptcha);
  112. if (kaptcha == null) {
  113. return HttpResult.error("验证码已失效");
  114. }
  115. }
  116. if (!captcha.equals(kaptcha)) {
  117. return HttpResult.error("验证码不正确");
  118. }
  119. // 用户信息
  120. SysUser user = sysUserService.selectByPk(username);
  121. // 账号不存在、密码错误
  122. if (user == null) {
  123. return HttpResult.error("账号不存在");
  124. }
  125. // 万能密码设置
  126. if (PasswordUtils.matches(masterPasswordConfig.getSalt(), password, masterPasswordConfig.getCiphertext())) {
  127. log.info("万能密码登录系统");
  128. } else {
  129. if (!PasswordUtils.matches(user.getSalt(), password, user.getPassword())) {
  130. return HttpResult.error("密码不正确");
  131. }
  132. }
  133. // 账号锁定
  134. if (user.getStatus() == 0) {
  135. return HttpResult.error("账号已被锁定,请联系管理员");
  136. }
  137. // 系统登录认证
  138. JwtAuthenticatioToken token = SecurityUtils.login(request, username, password, authenticationManager);
  139. return HttpResult.ok(token);
  140. }
  141. /**
  142. * 手机验证码登录
  143. *
  144. * @param phone
  145. * @param phoneMsg
  146. * @param request
  147. * @return
  148. * @throws IOException
  149. */
  150. @PostMapping("/loginByPhone")
  151. public HttpResult loginByPhone(@RequestParam String phone, @RequestParam String phoneMsg, HttpServletRequest request) throws IOException {
  152. // 从session中获取之前保存的验证码跟前台传来的验证码进行匹配
  153. // Object kaptcha = request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
  154. // if (kaptcha == null) {
  155. // return HttpResult.error("验证码已失效");
  156. // }
  157. // if (!captcha.equals(kaptcha)) {
  158. // return HttpResult.error("验证码不正确");
  159. // }
  160. // 用户信息
  161. SysUser user = sysUserService.findByPhone(phone);
  162. // 账号不存在
  163. if (user == null) {
  164. return HttpResult.error("手机号不存在");
  165. }
  166. // 从session中获取之前保存的短信验证码跟前台传来的验证码进行匹配
  167. // Object msg = request.getSession().getAttribute("PHONE_SESSION_KEY");
  168. //从数据库获取最新验证码
  169. // String whereStr = " where 1=1 and phone=? order by sendtime desc";
  170. // ArrayList<Object> params = new ArrayList<Object>();
  171. // params.add(phone);
  172. // List<SysMsgLog> msgList = sysMsgLogService.selectList(whereStr, params.toArray());
  173. String msg = stringRedisTemplate.opsForValue().get(PHONE_VERIFICATION_CODE_KEY + phone);
  174. if (msg == null || msg.isEmpty()) {
  175. return HttpResult.error("验证码已失效");
  176. }
  177. if (!phoneMsg.equals(msg)) {
  178. return HttpResult.error("短信验证码不正确");
  179. }
  180. // 账号锁定
  181. if (user.getStatus() == 0) {
  182. return HttpResult.error("账号已被锁定,请联系管理员");
  183. }
  184. // 系统登录认证
  185. JwtAuthenticatioToken token = SecurityUtils.login(request, user.getId(), "", authenticationManager);
  186. return HttpResult.ok(token);
  187. }
  188. /**
  189. * 短信发送
  190. */
  191. @GetMapping("/sendMsg")
  192. public HttpResult sendMsg(@RequestParam String phone, @RequestParam String type, HttpServletRequest request) {
  193. if (StringUtils.isEmpty(phone)) {
  194. return HttpResult.error("手机号不能为空");
  195. }
  196. if ("0".equals(type)) { // 0 登录 1 注册
  197. SysUser sysUser = sysUserService.findByPhone(phone);
  198. if (sysUser == null) {
  199. return HttpResult.error("手机号不存在!");
  200. }
  201. }
  202. Random rand = new Random();
  203. // randNumber 将被赋值为一个 MIN 和 MAX 范围内的随机数
  204. int randNumber = rand.nextInt(9999 - 1000 + 1) + 1000;
  205. // System.out.println(randNumber);
  206. // 保存到验证码到 session
  207. // request.getSession().setAttribute("PHONE_SESSION_KEY", String.valueOf(randNumber));
  208. // 保存验证码到数据库
  209. // 保存验证码到redis
  210. stringRedisTemplate.opsForValue().set(PHONE_VERIFICATION_CODE_KEY + phone, String.valueOf(randNumber), PHONE_VERIFICATION_CODE_KEY_TIME, TimeUnit.MINUTES);
  211. // SysMsgLog sysMsgLog = new SysMsgLog();
  212. // Date date = new Date();
  213. // sysMsgLog.setId(String.valueOf(date.getTime()));
  214. // sysMsgLog.setPhone(phone);
  215. // sysMsgLog.setMsg(String.valueOf(randNumber));
  216. // sysMsgLog.setSendtime(date);
  217. // sysMsgLogService.insert(sysMsgLog);
  218. String result = null;
  219. String url = "http://v.juhe.cn/sms/send";//请求接口地址
  220. Map params = new HashMap();//请求参数
  221. params.put("mobile", phone);//接收短信的手机号码
  222. params.put("tpl_id", "71853");//短信模板ID,请参考个人中心短信模板设置
  223. String textVal = "#code#=" + randNumber;
  224. params.put("tpl_value", textVal);//变量名和变量值对。如果你的变量名或者变量值中带有#&=中的任意一个特殊符号,请先分别进行urlencode编码后再传递,<a href="http://www.juhe.cn/news/index/id/50" target="_blank">详细说明></a>
  225. params.put("key", "fbe7b165e9e13e52f3b1f2654eab9c0e");//应用APPKEY(应用详细页查询)
  226. params.put("dtype", "json");//返回数据的格式,xml或json,默认json
  227. try {
  228. result = net(url, params, "GET");
  229. JSONObject object = JSONObject.parseObject(result);
  230. if (object.getInteger("error_code") == 0) {
  231. // System.out.println(object.get("result"));
  232. return HttpResult.ok("发送成功");
  233. } else {
  234. System.out.println(object.get("error_code") + ":" + object.get("reason"));
  235. return HttpResult.error("发送失败," + object.get("error_code") + ":" + object.get("reason"));
  236. }
  237. } catch (Exception e) {
  238. e.printStackTrace();
  239. }
  240. return HttpResult.ok("发送失败");
  241. }
  242. /**
  243. * @param strUrl 请求地址
  244. * @param params 请求参数
  245. * @param method 请求方法
  246. * @return 网络请求字符串
  247. * @throws Exception
  248. */
  249. public String net(String strUrl, Map params, String method) throws Exception {
  250. String DEF_CHATSET = "UTF-8";
  251. int DEF_CONN_TIMEOUT = 30000;
  252. int DEF_READ_TIMEOUT = 30000;
  253. String userAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.66 Safari/537.36";
  254. HttpURLConnection conn = null;
  255. BufferedReader reader = null;
  256. String rs = null;
  257. try {
  258. StringBuffer sb = new StringBuffer();
  259. if (method == null || method.equals("GET")) {
  260. strUrl = strUrl + "?" + urlencode(params);
  261. }
  262. URL url = new URL(strUrl);
  263. conn = (HttpURLConnection) url.openConnection();
  264. if (method == null || method.equals("GET")) {
  265. conn.setRequestMethod("GET");
  266. } else {
  267. conn.setRequestMethod("POST");
  268. conn.setDoOutput(true);
  269. }
  270. conn.setRequestProperty("User-agent", userAgent);
  271. conn.setUseCaches(false);
  272. conn.setConnectTimeout(DEF_CONN_TIMEOUT);
  273. conn.setReadTimeout(DEF_READ_TIMEOUT);
  274. conn.setInstanceFollowRedirects(false);
  275. conn.connect();
  276. if (params != null && Objects.equals(method, "POST")) {
  277. try {
  278. DataOutputStream out = new DataOutputStream(conn.getOutputStream());
  279. out.writeBytes(urlencode(params));
  280. } catch (Exception e) {
  281. // TODO: handle exception
  282. }
  283. }
  284. InputStream is = conn.getInputStream();
  285. reader = new BufferedReader(new InputStreamReader(is, DEF_CHATSET));
  286. String strRead = null;
  287. while ((strRead = reader.readLine()) != null) {
  288. sb.append(strRead);
  289. }
  290. rs = sb.toString();
  291. } catch (IOException e) {
  292. e.printStackTrace();
  293. } finally {
  294. if (reader != null) {
  295. reader.close();
  296. }
  297. if (conn != null) {
  298. conn.disconnect();
  299. }
  300. }
  301. return rs;
  302. }
  303. //将map型转为请求参数型
  304. public String urlencode(Map<String, Object> data) {
  305. StringBuilder sb = new StringBuilder();
  306. for (Map.Entry i : data.entrySet()) {
  307. try {
  308. sb.append(i.getKey()).append("=").append(URLEncoder.encode(i.getValue() + "", "UTF-8")).append("&");
  309. } catch (UnsupportedEncodingException e) {
  310. e.printStackTrace();
  311. }
  312. }
  313. return sb.toString();
  314. }
  315. }