SysLoginController.java 12 KB

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