BaseController.java 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. package com.uas.sso.controller;
  2. import com.alibaba.fastjson.JSON;
  3. import com.uas.message.mail.service.MailService;
  4. import com.uas.message.sms.service.SmsService;
  5. import com.uas.sso.core.Const;
  6. import com.uas.sso.core.PasswordStrength;
  7. import com.uas.sso.entity.Setting;
  8. import com.uas.sso.entity.Token;
  9. import com.uas.sso.exception.VisibleError;
  10. import com.uas.sso.service.SettingService;
  11. import com.uas.sso.service.TokenService;
  12. import com.uas.sso.util.StringUtil;
  13. import org.springframework.beans.factory.annotation.Autowired;
  14. import org.springframework.http.HttpHeaders;
  15. import org.springframework.http.HttpStatus;
  16. import org.springframework.http.MediaType;
  17. import org.springframework.http.ResponseEntity;
  18. import org.springframework.ui.ModelMap;
  19. import org.springframework.util.StringUtils;
  20. import javax.servlet.http.HttpServletRequest;
  21. import javax.servlet.http.HttpServletResponse;
  22. import java.io.IOException;
  23. import java.io.PrintWriter;
  24. /**
  25. * controller基础类
  26. *
  27. * @author yingp
  28. */
  29. public class BaseController {
  30. protected static final String defultCharset = "UTF-8";
  31. @Autowired
  32. protected HttpServletRequest request;
  33. @Autowired
  34. protected HttpServletResponse response;
  35. @Autowired
  36. protected TokenService tokenService;
  37. @Autowired
  38. protected SmsService smsService;
  39. @Autowired
  40. protected MailService mailService;
  41. @Autowired
  42. protected SettingService settingService;
  43. protected static boolean isSuccess(ModelMap map) {
  44. return Boolean.TRUE.equals(map.get("success"));
  45. }
  46. protected static Object getContent(ModelMap map) {
  47. return map.get("content");
  48. }
  49. protected static ModelMap success() {
  50. return new ModelMap("success", true);
  51. }
  52. protected static ModelMap success(Object data) {
  53. return new ModelMap("success", true).addAttribute("content", data);
  54. }
  55. protected static ModelMap error(String errMsg) {
  56. return new ModelMap("error", true).addAttribute("errMsg", errMsg);
  57. }
  58. protected static ModelMap error(Object detail) {
  59. return new ModelMap("error", true).addAttribute("errDetail", detail);
  60. }
  61. protected static ModelMap error(String errCode, String errMsg) {
  62. return new ModelMap("error", true).addAttribute("errCode", errCode).addAttribute("errMsg", errMsg);
  63. }
  64. /**
  65. * 输出json格式
  66. *
  67. * @param obj
  68. * @throws IOException
  69. */
  70. protected void printJson(Object obj) throws IOException {
  71. response.addHeader("Content-Type", "application/json; charset=" + defultCharset);
  72. PrintWriter printWriter = response.getWriter();
  73. printWriter.append(JSON.toJSONString(obj));
  74. printWriter.flush();
  75. printWriter.close();
  76. }
  77. /**
  78. * 响应Ajax请求
  79. *
  80. * @param content 响应内容
  81. * @throws IOException
  82. */
  83. protected void printJsonP(String callback, Object content) throws IOException {
  84. if (!content.getClass().isAssignableFrom(String.class)) {
  85. content = JSON.toJSON(content);
  86. }
  87. response.setContentType("text/html;charset=" + defultCharset);
  88. PrintWriter out = response.getWriter();
  89. out.print(callback + "(" + content + ")");
  90. out.flush();
  91. }
  92. /**
  93. * 输出流
  94. *
  95. * @param fileName 文件名
  96. * @param bytes
  97. * @throws IOException
  98. */
  99. protected ResponseEntity<byte[]> outputStream(String fileName, byte[] bytes) {
  100. HttpHeaders headers = new HttpHeaders();
  101. headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
  102. headers.setContentDispositionFormData("attachment", fileName);
  103. return new ResponseEntity<byte[]>(bytes, headers, HttpStatus.CREATED);
  104. }
  105. /**
  106. * 校验密码强度
  107. *
  108. * @param password 密码
  109. * @return PasswordStrength枚举
  110. * @throws VisibleError 用户可见异常
  111. */
  112. protected PasswordStrength checkPasswordLevel(String password) throws VisibleError {
  113. String strongRegex = "^(?=.{8,20})(((?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]))|((?=.*[0-9])((?=.*[a-zA-Z]))(?=.*[^a-zA-Z0-9]))).*$";
  114. String mediumRegex = "^(?=.{8,20})(((?=.*[0-9])(?=.*[a-z]))|((?=.*[0-9])(?=.*[A-Z]))).*$";
  115. if (password == null) {
  116. throw new VisibleError("密码不能为空");
  117. }
  118. if (password.matches(strongRegex)) {
  119. return PasswordStrength.STRONG;
  120. } else if (password.matches(mediumRegex)) {
  121. return PasswordStrength.MEDIUM;
  122. } else {
  123. return PasswordStrength.WEAK;
  124. }
  125. }
  126. /**
  127. * 获取验证码
  128. *
  129. * @param mobile 手机号
  130. * @param email 邮箱
  131. * @return tokenId
  132. */
  133. protected String getValidCode(String mobile, String email) {
  134. // 随机获得验证码
  135. String code = StringUtil.getRandomNumber(6);
  136. Token token = new Token(code, 10 * 60);
  137. System.out.println(code);
  138. // 设置绑定手机,防止获取验证码之后修改手机号
  139. token.setMobile(mobile);
  140. token.setEmail(email);
  141. // 将token存到Redis服务器上
  142. tokenService.save(token);
  143. // 将验证码发送到手机上
  144. ModelMap data = new ModelMap();
  145. data.put("checkcode", code);
  146. // 手机短信
  147. try {
  148. if (!StringUtils.isEmpty(mobile)) {
  149. Setting smsTplId = settingService.findOne("templateForSendSmsWhenRegister");
  150. if (!StringUtils.isEmpty(smsTplId)) {
  151. smsService.send(smsTplId.getValue(), mobile, new Object[]{code});
  152. }
  153. }
  154. } catch (Exception e) {
  155. e.printStackTrace();
  156. }
  157. // 邮件
  158. try {
  159. if (!StringUtils.isEmpty(email)) {
  160. Setting mailTplId = settingService.findOne("templateForSendEmailWhenRegister");
  161. if (!StringUtils.isEmpty(mailTplId)) {
  162. mailService.send(mailTplId.getValue(), email, data);
  163. }
  164. }
  165. } catch (Exception e) {
  166. e.printStackTrace();
  167. }
  168. // 返回tokenId
  169. return token.getId();
  170. }
  171. /**
  172. * 获取手机号验证码
  173. *
  174. * @param mobile 手机号
  175. * @return tokenId
  176. */
  177. protected String getMobileCode(String mobile) {
  178. return getValidCode(mobile, null);
  179. }
  180. /**
  181. * 获取邮箱验证码
  182. *
  183. * @param email 邮箱
  184. * @return
  185. */
  186. protected String getEmailCode(String email) {
  187. return getValidCode(null, email);
  188. }
  189. /**
  190. * 校验验证码
  191. *
  192. * @param token 验证码tokenID
  193. * @param mobile 手机号
  194. * @param email 邮箱
  195. * @param code 验证码
  196. * @return
  197. * @throws VisibleError 校验失败则抛异常
  198. * 当参数异常,token过期或者token绑定的手机号不对时抛出此异常
  199. */
  200. protected void checkValidCode(String token, String mobile, String email, String code) {
  201. // 校验参数
  202. if (StringUtils.isEmpty(token) || StringUtils.isEmpty(code)) {
  203. throw new VisibleError("参数错误");
  204. }
  205. Token existToken = tokenService.findOne(token);
  206. if (existToken == null || existToken.isExpired()) {
  207. throw new VisibleError("验证码已经失效,请重新获取");
  208. }
  209. if (!StringUtils.isEmpty(existToken.getMobile()) && !existToken.getMobile().equals(mobile)) {
  210. throw new VisibleError("手机号被修改,请重新获取验证码");
  211. }
  212. if (!StringUtils.isEmpty(existToken.getEmail()) && !existToken.getEmail().equals(email)) {
  213. throw new VisibleError("手机号被修改,请重新获取验证码");
  214. }
  215. // 校验验证码
  216. String existCode = existToken.getBind().toString();
  217. if (!code.equals(existCode)) {
  218. throw new VisibleError("验证码错误");
  219. }
  220. }
  221. /**
  222. * 校验手机号验证码
  223. *
  224. * @param token 验证码tokenID
  225. * @param mobile 手机号
  226. * @param code 验证码
  227. */
  228. protected void checkMobileCode(String token, String mobile, String code) {
  229. checkValidCode(token, mobile, null, code);
  230. }
  231. /**
  232. * 校验手机号验证码
  233. *
  234. * @param token 验证码tokenID
  235. * @param email 邮箱
  236. * @param code 验证码
  237. */
  238. protected void checkEmailCode(String token, String email, String code) {
  239. checkValidCode(token, null, email, code);
  240. }
  241. /**
  242. * 校验手机号格式
  243. *
  244. * @param mobile 手机号
  245. * @param mobileArea 手机号所属区域
  246. */
  247. protected void checkMobile(String mobile, String mobileArea) {
  248. // 由于现在不考虑手机号所属区域,默认为中国大陆
  249. mobileArea = mobileArea == null ? Const.CONTINENT : mobileArea;
  250. // 校验手机号
  251. if (Const.CONTINENT.equals(mobileArea)) {
  252. if (!mobile.matches(Const.REGEXP_MOBILE_CONTINENT)) {
  253. throw new VisibleError("请输入正确的手机号格式");
  254. }
  255. } else if (Const.HONGKONG.equals(mobileArea)) {
  256. if (!mobile.matches(Const.REGEXP_MOBILE_HONGKONG)) {
  257. throw new VisibleError("请输入正确的手机号格式");
  258. }
  259. } else {
  260. throw new VisibleError("未找到所选地区");
  261. }
  262. }
  263. }