You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

84 lines
2.6 KiB

3 years ago
  1. package utils
  2. import (
  3. "errors"
  4. "time"
  5. "github.com/dgrijalva/jwt-go"
  6. "github.com/flipped-aurora/gin-vue-admin/server/global"
  7. "github.com/flipped-aurora/gin-vue-admin/server/model/system/request"
  8. )
  9. type JWT struct {
  10. SigningKey []byte
  11. }
  12. var (
  13. TokenExpired = errors.New("Token is expired")
  14. TokenNotValidYet = errors.New("Token not active yet")
  15. TokenMalformed = errors.New("That's not even a token")
  16. TokenInvalid = errors.New("Couldn't handle this token:")
  17. )
  18. func NewJWT() *JWT {
  19. return &JWT{
  20. []byte(global.GVA_CONFIG.JWT.SigningKey),
  21. }
  22. }
  23. func (j *JWT) CreateClaims(baseClaims request.BaseClaims) request.CustomClaims {
  24. claims := request.CustomClaims{
  25. BaseClaims: baseClaims,
  26. BufferTime: global.GVA_CONFIG.JWT.BufferTime, // 缓冲时间1天 缓冲时间内会获得新的token刷新令牌 此时一个用户会存在两个有效令牌 但是前端只留一个 另一个会丢失
  27. StandardClaims: jwt.StandardClaims{
  28. NotBefore: time.Now().Unix() - 1000, // 签名生效时间
  29. ExpiresAt: time.Now().Unix() + global.GVA_CONFIG.JWT.ExpiresTime, // 过期时间 7天 配置文件
  30. Issuer: global.GVA_CONFIG.JWT.Issuer, // 签名的发行者
  31. },
  32. }
  33. return claims
  34. }
  35. // 创建一个token
  36. func (j *JWT) CreateToken(claims request.CustomClaims) (string, error) {
  37. token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
  38. return token.SignedString(j.SigningKey)
  39. }
  40. // CreateTokenByOldToken 旧token 换新token 使用归并回源避免并发问题
  41. func (j *JWT) CreateTokenByOldToken(oldToken string, claims request.CustomClaims) (string, error) {
  42. v, err, _ := global.GVA_Concurrency_Control.Do("JWT:"+oldToken, func() (interface{}, error) {
  43. return j.CreateToken(claims)
  44. })
  45. return v.(string), err
  46. }
  47. // 解析 token
  48. func (j *JWT) ParseToken(tokenString string) (*request.CustomClaims, error) {
  49. token, err := jwt.ParseWithClaims(tokenString, &request.CustomClaims{}, func(token *jwt.Token) (i interface{}, e error) {
  50. return j.SigningKey, nil
  51. })
  52. if err != nil {
  53. if ve, ok := err.(*jwt.ValidationError); ok {
  54. if ve.Errors&jwt.ValidationErrorMalformed != 0 {
  55. return nil, TokenMalformed
  56. } else if ve.Errors&jwt.ValidationErrorExpired != 0 {
  57. // Token is expired
  58. return nil, TokenExpired
  59. } else if ve.Errors&jwt.ValidationErrorNotValidYet != 0 {
  60. return nil, TokenNotValidYet
  61. } else {
  62. return nil, TokenInvalid
  63. }
  64. }
  65. }
  66. if token != nil {
  67. if claims, ok := token.Claims.(*request.CustomClaims); ok && token.Valid {
  68. return claims, nil
  69. }
  70. return nil, TokenInvalid
  71. } else {
  72. return nil, TokenInvalid
  73. }
  74. }