jwt.go 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package middleware
  2. import (
  3. "errors"
  4. "github.com/golang-jwt/jwt/v4"
  5. "github.com/sirupsen/logrus"
  6. "strconv"
  7. "time"
  8. "lcfns/utils"
  9. "lcfns/global"
  10. "lcfns/model/common/response"
  11. "lcfns/model/system"
  12. "lcfns/service"
  13. "github.com/gin-gonic/gin"
  14. "go.uber.org/zap"
  15. )
  16. var jwtService = service.ServiceGroupApp.SystemServiceGroup.JwtService
  17. func JWTAuth() gin.HandlerFunc {
  18. return func(c *gin.Context) {
  19. // 我们这里jwt鉴权取头部信息 x-token 登录时回返回token信息 这里前端需要把token存储到cookie或者本地localStorage中 不过需要跟后端协商过期时间 可以约定刷新令牌或者重新登录
  20. token := c.Request.Header.Get("x-token")
  21. if token == "" {
  22. response.FailWithDetailed(gin.H{"reload": true}, "未登录或非法访问", c)
  23. c.Abort()
  24. return
  25. }
  26. if jwtService.IsBlacklist(token) {
  27. response.FailWithDetailed(gin.H{"reload": true}, "您的帐户异地登陆或令牌失效", c)
  28. c.Abort()
  29. return
  30. }
  31. j := utils.NewJWT()
  32. // parseToken 解析token包含的信息
  33. claims, err := j.ParseToken(token)
  34. if err != nil {
  35. if errors.Is(err, utils.TokenExpired) {
  36. response.FailWithDetailed(gin.H{"reload": true}, "授权已过期", c)
  37. c.Abort()
  38. return
  39. }
  40. response.FailWithDetailed(gin.H{"reload": true}, err.Error(), c)
  41. c.Abort()
  42. return
  43. }
  44. // 已登录用户被管理员禁用 需要使该用户的jwt失效 此处比较消耗性能 如果需要 请自行打开
  45. // 用户被删除的逻辑 需要优化 此处比较消耗性能 如果需要 请自行打开
  46. //if user, err := userService.FindUserByUuid(claims.UUID.String()); err != nil || user.Enable == 2 {
  47. // _ = jwtService.JsonInBlacklist(system.JwtBlacklist{Jwt: token})
  48. // response.FailWithDetailed(gin.H{"reload": true}, err.Error(), c)
  49. // c.Abort()
  50. //}
  51. if claims.ExpiresAt.Unix()-time.Now().Unix() < claims.BufferTime {
  52. dr, _ := utils.ParseDuration(global.Config.JWT.ExpiresTime)
  53. claims.ExpiresAt = jwt.NewNumericDate(time.Now().Add(dr))
  54. newToken, _ := j.CreateTokenByOldToken(token, *claims)
  55. newClaims, _ := j.ParseToken(newToken)
  56. c.Header("new-token", newToken)
  57. c.Header("new-expires-at", strconv.FormatInt(newClaims.ExpiresAt.Unix(), 10))
  58. if global.Config.System.UseMultipoint {
  59. RedisJwtToken, err := jwtService.GetRedisJWT(newClaims.Username)
  60. if err != nil {
  61. logrus.Error("get redis jwt failed", zap.Error(err))
  62. } else { // 当之前的取成功时才进行拉黑操作
  63. _ = jwtService.JsonInBlacklist(system.JwtBlacklist{Jwt: RedisJwtToken})
  64. }
  65. // 无论如何都要记录当前的活跃状态
  66. _ = jwtService.SetRedisJWT(newToken, newClaims.Username)
  67. }
  68. }
  69. c.Set("claims", claims)
  70. c.Next()
  71. }
  72. }