62 lines
1.2 KiB
Go
62 lines
1.2 KiB
Go
package jwt
|
|
|
|
import (
|
|
"errors"
|
|
"time"
|
|
|
|
"github.com/dgrijalva/jwt-go"
|
|
)
|
|
|
|
var JwtKey = []byte("bitwsd@hello qinshihuang")
|
|
var ValidTime = 3600 * 24 * 7
|
|
|
|
type User struct {
|
|
UserId int64 `json:"user_id"`
|
|
}
|
|
type CustomClaims struct {
|
|
User
|
|
jwt.StandardClaims
|
|
}
|
|
|
|
func CreateToken(user User) (string, error) {
|
|
expire := time.Now().Add(time.Duration(ValidTime) * time.Second)
|
|
claims := &CustomClaims{
|
|
User: user,
|
|
StandardClaims: jwt.StandardClaims{
|
|
ExpiresAt: expire.Unix(),
|
|
IssuedAt: time.Now().Unix(),
|
|
},
|
|
}
|
|
|
|
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
|
|
|
t, err := token.SignedString(JwtKey)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
|
|
return "Bearer " + t, nil
|
|
}
|
|
|
|
func ParseToken(signToken string) (*CustomClaims, error) {
|
|
token, err := jwt.ParseWithClaims(signToken, &CustomClaims{}, func(token *jwt.Token) (interface{}, error) {
|
|
return JwtKey, nil
|
|
})
|
|
|
|
if err != nil {
|
|
if ve, ok := err.(*jwt.ValidationError); ok {
|
|
if ve.Errors&jwt.ValidationErrorExpired != 0 {
|
|
return nil, errors.New("token expired")
|
|
}
|
|
}
|
|
return nil, err
|
|
}
|
|
|
|
claims, _ := token.Claims.(*CustomClaims)
|
|
if claims == nil || !token.Valid {
|
|
return nil, errors.New("token invalid")
|
|
}
|
|
|
|
return claims, nil
|
|
}
|