54 lines
1.2 KiB
Go
54 lines
1.2 KiB
Go
package jwt
|
|
|
|
import (
|
|
"fmt"
|
|
"time"
|
|
|
|
gojwt "github.com/golang-jwt/jwt"
|
|
)
|
|
|
|
type TokenClaim struct {
|
|
User string `json:"-"`
|
|
UserID uint64 `json:"userId"`
|
|
gojwt.StandardClaims
|
|
Expiration time.Duration `json:"-"`
|
|
}
|
|
|
|
func ParseTokenClaim(token string, secret string) (*TokenClaim, error) {
|
|
tokenClaims, err := gojwt.ParseWithClaims(token, &TokenClaim{}, func(token *gojwt.Token) (interface{}, error) {
|
|
return []byte(secret), nil
|
|
})
|
|
|
|
if tokenClaims != nil {
|
|
if claims, ok := tokenClaims.Claims.(*TokenClaim); ok {
|
|
return claims, nil
|
|
}
|
|
}
|
|
//
|
|
return nil, err
|
|
}
|
|
|
|
func NewTokenClaim(user string, expiration time.Duration, uid uint64) (*TokenClaim, error) {
|
|
if int64(expiration) < 0 {
|
|
return nil, fmt.Errorf("expired at invalid")
|
|
}
|
|
claim := TokenClaim{
|
|
User: user,
|
|
StandardClaims: gojwt.StandardClaims{
|
|
// ExpiresAt: time.Now().Add(expiration).Unix(),
|
|
},
|
|
UserID: uid,
|
|
}
|
|
return &claim, nil
|
|
}
|
|
|
|
func (t *TokenClaim) InValid() bool {
|
|
return t.Valid() != nil
|
|
}
|
|
|
|
func (t *TokenClaim) String(secret string) (string, error) {
|
|
tokenClaims := gojwt.NewWithClaims(gojwt.SigningMethodHS256, t)
|
|
token, err := tokenClaims.SignedString([]byte(secret))
|
|
return token, err
|
|
}
|