github.com/jtzjtz/kit@v1.0.2/sign/jwt.go (about)

     1  package sign
     2  
     3  import (
     4  	"errors"
     5  	"github.com/dgrijalva/jwt-go"
     6  	"time"
     7  )
     8  
     9  type JWT struct {
    10  	SigningKey []byte
    11  }
    12  
    13  var (
    14  	TokenExpired     error = errors.New("Token is expired")
    15  	TokenNotValidYet error = errors.New("Token not active yet")
    16  	TokenMalformed   error = errors.New("That's not even a token")
    17  	TokenInvalid     error = errors.New("Couldn't handle this token:")
    18  )
    19  
    20  type CustomClaims struct {
    21  	UserId     int    `json:"user_id"`
    22  	CreateTime string `json:"create_time"`
    23  	jwt.StandardClaims
    24  }
    25  
    26  func InitJWT(signKey string) *JWT {
    27  	return &JWT{
    28  		[]byte(signKey),
    29  	}
    30  }
    31  
    32  /**
    33   * 创建JWT  token信息
    34   */
    35  func (j *JWT) CreateToken(claims CustomClaims) (string, error) {
    36  	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
    37  	return token.SignedString(j.SigningKey)
    38  }
    39  
    40  /**
    41   * 验证JWT  token信息
    42   */
    43  func (j *JWT) ParseToken(tokenString string) (*CustomClaims, error) {
    44  	token, err := jwt.ParseWithClaims(tokenString, &CustomClaims{}, func(token *jwt.Token) (interface{}, error) {
    45  		return j.SigningKey, nil
    46  	})
    47  
    48  	// 当token不存在时
    49  	if token == nil {
    50  		return nil, TokenInvalid
    51  	}
    52  
    53  	if err != nil {
    54  		if ve, ok := err.(*jwt.ValidationError); ok {
    55  			if ve.Errors&jwt.ValidationErrorMalformed != 0 {
    56  				return nil, TokenMalformed
    57  			} else if ve.Errors&jwt.ValidationErrorExpired != 0 {
    58  				return token.Claims.(*CustomClaims), TokenExpired
    59  			} else if ve.Errors&jwt.ValidationErrorNotValidYet != 0 {
    60  				return nil, TokenNotValidYet
    61  			} else {
    62  				return nil, TokenInvalid
    63  			}
    64  		}
    65  	}
    66  
    67  	if claims, ok := token.Claims.(*CustomClaims); ok && token.Valid {
    68  		return claims, nil
    69  	}
    70  	return nil, TokenInvalid
    71  }
    72  
    73  /**
    74   * 刷新JWT  token信息
    75   */
    76  func (j *JWT) RefreshToken(tokenString string) (string, error) {
    77  	jwt.TimeFunc = func() time.Time {
    78  		return time.Unix(0, 0)
    79  	}
    80  	token, err := jwt.ParseWithClaims(tokenString, &CustomClaims{}, func(token *jwt.Token) (interface{}, error) {
    81  		return j.SigningKey, nil
    82  	})
    83  	if err != nil {
    84  		return "", err
    85  	}
    86  	if claims, ok := token.Claims.(*CustomClaims); ok && token.Valid {
    87  		jwt.TimeFunc = time.Now
    88  		claims.StandardClaims.ExpiresAt = time.Now().Add(1 * time.Hour).Unix()
    89  		return j.CreateToken(*claims)
    90  	}
    91  	return "", TokenInvalid
    92  }