init repo
This commit is contained in:
61
pkg/jwt/jwt.go
Normal file
61
pkg/jwt/jwt.go
Normal file
@@ -0,0 +1,61 @@
|
||||
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
|
||||
}
|
||||
Reference in New Issue
Block a user