MSP-1068 init token service
This commit is contained in:
1 parent
932d5cb725
commit
e2e8bf5f45
1 file changed
+26
-16
+26
-16
@@ -1,13 +1,10 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/dgrijalva/jwt-go"
|
||||
"github.com/integration-system/isp-lib/v2/config"
|
||||
"github.com/pkg/errors"
|
||||
"msp-admin-service/conf"
|
||||
)
|
||||
|
||||
type customClaims struct {
|
||||
@@ -15,37 +12,50 @@ type customClaims struct {
|
||||
jwt.StandardClaims
|
||||
}
|
||||
|
||||
func GenerateToken(id int64) (string, string, error) {
|
||||
type Token struct {
|
||||
ttl time.Duration
|
||||
secretKey string
|
||||
}
|
||||
|
||||
func NewToken(ttl time.Duration, secretKey string) Token {
|
||||
return Token{
|
||||
ttl: ttl,
|
||||
secretKey: secretKey,
|
||||
}
|
||||
}
|
||||
|
||||
func (t Token) GenerateToken(id int64) (string, string, error) {
|
||||
expired := ""
|
||||
claims := customClaims{Id: id}
|
||||
cfg := config.GetRemote().(*conf.RemoteConfig)
|
||||
if cfg.ExpireSec != 0 {
|
||||
exp := time.Now().Add(time.Second * time.Duration(cfg.ExpireSec))
|
||||
|
||||
if t.ttl != 0 {
|
||||
exp := time.Now().Add(t.ttl)
|
||||
expired = exp.String()
|
||||
claims.ExpiresAt = exp.Unix()
|
||||
}
|
||||
tokenString, err := jwt.NewWithClaims(jwt.SigningMethodHS256, claims).SignedString([]byte(cfg.SecretKey))
|
||||
|
||||
tokenString, err := jwt.NewWithClaims(jwt.SigningMethodHS256, claims).SignedString([]byte(t.secretKey))
|
||||
if err != nil {
|
||||
return "", "", err
|
||||
return "", "", errors.WithMessage(err, "generate jwt with claims")
|
||||
}
|
||||
|
||||
return tokenString, expired, nil
|
||||
}
|
||||
|
||||
func GetUserId(token string) (int64, error) {
|
||||
cfg := config.GetRemote().(*conf.RemoteConfig)
|
||||
func (t Token) GetUserId(token string) (int64, error) {
|
||||
parsed, err := jwt.ParseWithClaims(token, &customClaims{}, func(token *jwt.Token) (i interface{}, e error) {
|
||||
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
|
||||
return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
|
||||
return nil, errors.Errorf("Unexpected signing method: %v", token.Header["alg"])
|
||||
}
|
||||
return []byte(cfg.SecretKey), nil
|
||||
return []byte(t.secretKey), nil
|
||||
})
|
||||
if err != nil {
|
||||
return 0, err
|
||||
return 0, errors.WithMessage(err, "parse jwt with claims")
|
||||
}
|
||||
|
||||
if claims, ok := parsed.Claims.(*customClaims); ok && parsed.Valid {
|
||||
return claims.Id, nil
|
||||
} else {
|
||||
return 0, errors.New("token is invalid")
|
||||
}
|
||||
|
||||
return 0, errors.New("token is invalid")
|
||||
}
|
||||
Reference in new issue
Block a user