BaseController.java 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package com.fdkankan.sale.controller;
  2. import com.auth0.jwt.JWT;
  3. import com.auth0.jwt.interfaces.DecodedJWT;
  4. import com.baomidou.mybatisplus.core.toolkit.StringUtils;
  5. import com.fdkankan.sale.common.ResultCode;
  6. import com.fdkankan.sale.entity.SysUser;
  7. import com.fdkankan.sale.exception.BusinessException;
  8. import com.fdkankan.sale.service.ISysUserService;
  9. import org.springframework.beans.factory.annotation.Autowired;
  10. import org.springframework.stereotype.Component;
  11. import javax.servlet.http.HttpServletRequest;
  12. import javax.servlet.http.HttpServletResponse;
  13. import static com.baomidou.mybatisplus.core.toolkit.IdWorker.getId;
  14. @Component
  15. public class BaseController {
  16. @Autowired
  17. protected HttpServletRequest request;
  18. @Autowired
  19. ISysUserService sysUserService;
  20. @Autowired
  21. protected HttpServletResponse response;
  22. protected String getToken(){
  23. return request.getHeader("token");
  24. }
  25. protected Long getUserId(){
  26. String token = request.getHeader("token");
  27. if(StringUtils.isBlank(token)){
  28. return null;
  29. }
  30. try {
  31. DecodedJWT jwt = JWT.decode(token);
  32. Long userId = jwt.getClaim("userId").asLong();
  33. return sysUserService.getByManageId(userId).getId();
  34. }catch (Exception e){
  35. return null;
  36. }
  37. }
  38. protected SysUser getUser(){
  39. String token = request.getHeader("token");
  40. if(StringUtils.isBlank(token)){
  41. return null;
  42. }
  43. try {
  44. DecodedJWT jwt = JWT.decode(token);
  45. Long userId = jwt.getClaim("userId").asLong();
  46. return sysUserService.getByManageId(userId);
  47. }catch (Exception e){
  48. return null;
  49. }
  50. }
  51. public static void main(String[] args) {
  52. String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsb2dpblR5cGUiOiJsb2dpbiIsImxvZ2luSWQiOjEsImRldmljZSI6ImRlZmF1bHQtZGV2aWNlIiwiZWZmIjotMSwicm5TdHIiOiJ5TUJRdkdDQzk2OURZNDJOaGVueEhuYzI4VUp4Q3MxYSIsInVzZXJJZCI6MSwiaXNBZG1pbiI6MSwidXNlck5hbWUiOiJzdXBlci1hZG1pbiIsIm5pY2tOYW1lIjoi6LaF57qn566h55CG5ZGYIn0.hnLrJoVWLwkWIwWdlUoBoWn2-ETepyI9l5AiLx3ji8M";
  53. DecodedJWT jwt = JWT.decode(token);
  54. Long userId = jwt.getClaim("userId").asLong();
  55. System.out.println(userId);
  56. }
  57. }