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.

45 lines
960 B

package common
import (
"expenses/model"
"github.com/dgrijalva/jwt-go"
"time"
)
var jwtKey = []byte("a_secret_key")
type Claims struct {
UserId uint
jwt.StandardClaims
}
func ReleaseToken(user model.User) (string, error) {
// 设置Token过期时间
expirationTime := time.Now().Add(7 * 24 * time.Hour)
claims := Claims{
UserId: user.ID,
StandardClaims: jwt.StandardClaims{
ExpiresAt: expirationTime.Unix(),
IssuedAt: time.Now().Unix(),
Issuer: "github.com/zggsong/expenses",
Subject: "user token",
},
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
tokenString, err := token.SignedString(jwtKey)
if err != nil {
return "", err
}
return tokenString, nil
}
func ParseToken(tokenString string) (*jwt.Token, *Claims, error) {
claims := &Claims{}
token, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (interface{}, error) {
return jwtKey, nil
})
return token, claims, err
}