fix get user by token method
This commit is contained in:
1 parent
8f2a6a58f2
commit
0d956b6bf6
4 files changed
+69
-7
No files matched your search
@@ -0,0 +1,50 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/dgrijalva/jwt-go"
|
||||
"github.com/integration-system/isp-lib/config"
|
||||
"github.com/pkg/errors"
|
||||
"msp-admin-service/conf"
|
||||
"time"
|
||||
)
|
||||
|
||||
type customClaims struct {
|
||||
Id int64
|
||||
jwt.StandardClaims
|
||||
}
|
||||
|
||||
func 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))
|
||||
expired = exp.String()
|
||||
claims.ExpiresAt = exp.Unix()
|
||||
}
|
||||
tokenString, err := jwt.NewWithClaims(jwt.SigningMethodHS256, claims).SignedString([]byte(cfg.SecretKey))
|
||||
if err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
return tokenString, expired, nil
|
||||
}
|
||||
|
||||
func GetUserId(token string) (int64, error) {
|
||||
cfg := config.GetRemote().(*conf.RemoteConfig)
|
||||
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 []byte(cfg.SecretKey), nil
|
||||
})
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
if claims, ok := parsed.Claims.(*customClaims); ok && parsed.Valid {
|
||||
return claims.Id, nil
|
||||
} else {
|
||||
return 0, errors.New("token is invalid")
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user