PageRenderTime 59ms CodeModel.GetById 27ms RepoModel.GetById 1ms app.codeStats 0ms

/src/main/java/com/penuel/mythopoet/controllers/AuthWithoutLoginController.java

https://gitlab.com/tycoon/mythopoet
Java | 134 lines | 105 code | 16 blank | 13 comment | 10 complexity | dccc8a5bfbd150a10d26c8b9b4a0110d MD5 | raw file
  1. package com.penuel.mythopoet.controllers;
  2. import java.util.Date;
  3. import java.util.SortedMap;
  4. import javax.servlet.http.Cookie;
  5. import javax.servlet.http.HttpServletRequest;
  6. import javax.servlet.http.HttpServletResponse;
  7. import org.apache.commons.lang3.StringUtils;
  8. import org.apache.commons.lang3.math.NumberUtils;
  9. import org.slf4j.Logger;
  10. import org.slf4j.LoggerFactory;
  11. import org.springframework.beans.factory.annotation.Autowired;
  12. import org.springframework.stereotype.Controller;
  13. import org.springframework.ui.Model;
  14. import org.springframework.web.bind.annotation.CookieValue;
  15. import org.springframework.web.bind.annotation.RequestMapping;
  16. import org.springframework.web.bind.annotation.RequestMethod;
  17. import org.springframework.web.bind.annotation.RequestParam;
  18. import org.springframework.web.bind.annotation.ResponseBody;
  19. import com.alibaba.fastjson.JSONObject;
  20. import com.penuel.mythopoet.model.WxAuthUser;
  21. import com.penuel.mythopoet.service.WxAuthWithoutUserService;
  22. import com.penuel.mythopoet.utils.ResponseUtil;
  23. @Controller
  24. @RequestMapping("/authWithoutLogin")
  25. public class AuthWithoutLoginController {
  26. private static final Logger LOGGER = LoggerFactory
  27. .getLogger(AuthWithoutLoginController.class);
  28. @Autowired
  29. private WxAuthWithoutUserService wxAuthService;
  30. /**
  31. * 获取wx code的url回调地址
  32. *
  33. * @param model
  34. * @param code
  35. * 返回需要的code,每次用户授权带上的code将不一样,code只能使用一次,5分钟未被使用自动过期<br/>
  36. * 若用户禁止授权,则重定向后不会带上code参数
  37. * @param state userId,currentUrl
  38. * @return 返回当前页面
  39. */
  40. @RequestMapping(value = "/wxcode", method = RequestMethod.GET, produces = "application/json;charset=utf-8")
  41. public String wxcode(Model model,
  42. @RequestParam(value = "code", defaultValue = "") String code,
  43. @RequestParam(value = "state", defaultValue = "") String state,
  44. HttpServletRequest request, HttpServletResponse response) {
  45. long userId = -1;
  46. String currentUrl="/";
  47. try {
  48. //String[] stateArray = state.split("@");
  49. //userId = NumberUtils.toLong(stateArray[0]);
  50. //currentUrl = stateArray[1];
  51. if (StringUtils.isBlank(code)) {
  52. return "redirect:"+currentUrl;
  53. }
  54. WxAuthUser wxAuthUser = wxAuthService.getAccessToken(code, userId);
  55. boolean flag = false;
  56. Cookie[] cookies = request.getCookies();
  57. for (int i = 0; i < cookies.length; i++) {
  58. Cookie cookie = cookies[i];
  59. if ("openId".equals(cookie.getName())) {
  60. flag = true;
  61. break;
  62. }
  63. }
  64. if (!flag) {
  65. Cookie c = new Cookie("openId", wxAuthUser.getOpenId());
  66. c.setMaxAge(1000); // set expire time to 1000 sec
  67. c.setPath("/");
  68. response.addCookie(c); // put cookie in response
  69. LOGGER.info("authWithoutLogin.wxcode : add cookie openId ="+wxAuthUser.getOpenId());
  70. }
  71. return "redirect:"+currentUrl;
  72. } catch (Exception e) {
  73. LOGGER.error("AuthWithoutLoginController.wxcode Error:code=" + code
  74. + ",state=" + state, e);
  75. }
  76. return "redirect:"+currentUrl;
  77. }
  78. @RequestMapping(value = "/ticket", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
  79. @ResponseBody
  80. public String jsapiTicket(Model model, @RequestParam("openId") String openId,@RequestParam("userId") long userId,@RequestParam("currentUrl") String currentUrl) {
  81. try {
  82. WxAuthUser wxAuthUser;
  83. if (openId==null||openId.trim().equals("")) {
  84. String authUrl = wxAuthService.authorizeURL(userId,currentUrl);
  85. return ResponseUtil.result(1001, "微信授权", authUrl);
  86. }else{
  87. wxAuthUser = wxAuthService.getByOpenId(openId);
  88. if(wxAuthUser==null){
  89. String authUrl = wxAuthService.authorizeURL(userId,currentUrl);
  90. return ResponseUtil.result(1001, "微信授权", authUrl);
  91. }
  92. }
  93. boolean refreshTicket = false;
  94. long millSecond = (new Date()).getTime()
  95. - wxAuthUser.getJsapiRefreshTime().getTime();
  96. if (StringUtils.isBlank(wxAuthUser.getJsapiTicket())) {
  97. refreshTicket = true;
  98. } else if (millSecond + 5 * 60 * 1000 > wxAuthUser
  99. .getJsapiExpiresIn() * 1000) {
  100. refreshTicket = true;
  101. }
  102. LOGGER.info("jsapiTicket.wxAuthUser ="
  103. + JSONObject.toJSONString(wxAuthUser) + ",millSecond="
  104. + millSecond);
  105. if (refreshTicket) {
  106. wxAuthService.refreshJsapiTicket(wxAuthUser);
  107. }
  108. SortedMap<Object, Object> map = wxAuthService.fillJsapiTicketParam(
  109. wxAuthUser.getJsapiTicket(), currentUrl);
  110. LOGGER.info("AuthController.jsapiTicket result="
  111. + JSONObject.toJSONString(map));
  112. return ResponseUtil.result(0, "OK", map);
  113. } catch (Exception e) {
  114. LOGGER.error("AuthController.jsapiTicket Error:userId=" + userId, e);
  115. return ResponseUtil.result(1, "获取jsAPI初始化参数失败", null);
  116. }
  117. }
  118. }