123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566 |
- package utils
- import (
- "gd_gateway/errors"
- "strconv"
- "time"
- "gd_gateway/common.in/config"
- "github.com/dgrijalva/jwt-go"
- )
- type UtimesClaims struct {
- Jti string `json:"jti"`
- jwt.StandardClaims
- }
- type UserClaims struct {
- Uid int64 `json:"uid"`
- UserName string `json:"user_name"`
- //Password string `json:"password"`
- jwt.StandardClaims
- }
- type UtimesIssuer int
- const (
- UserJWTKey = "be3bc479a23b6161c229b0a27359d869"
- )
- func ProductToken(uid int64, userName string) (string, error) {
- expired, _ := config.Conf.Cgi.GdGateway.TokenExpired.Int64()
- claims := UserClaims{
- uid,
- userName,
- jwt.StandardClaims{
- ExpiresAt: time.Now().Unix() + expired, //3600*2, //过期时间
- Subject: strconv.FormatInt(uid, 10), //uid
- IssuedAt: time.Now().Unix(), //生成时间
- NotBefore: time.Now().Unix(),
- },
- }
- plain := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
- return plain.SignedString([]byte(UserJWTKey))
- }
- func ParseToken(tokenString string) (int64, string, error) {
- token, err := jwt.ParseWithClaims(tokenString, &UserClaims{}, func(token *jwt.Token) (interface{}, error) {
- return []byte(UserJWTKey), nil
- })
- if err != nil {
- switch err.(*jwt.ValidationError).Errors {
- case jwt.ValidationErrorExpired:
- return 0, "", errors.UserTokenExpire
- default:
- return 0, "", errors.UserTokenError
- }
- }
- if clams, ok := token.Claims.(*UserClaims); ok {
- return clams.Uid, clams.UserName, nil
- } else {
- return 0, "", errors.UserTokenError
- }
- }
|