feat: add jwt
This commit is contained in:
66
utils/jwt.go
Normal file
66
utils/jwt.go
Normal file
@@ -0,0 +1,66 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"nCovTrack-Backend/global"
|
||||
"time"
|
||||
|
||||
"github.com/golang-jwt/jwt/v4"
|
||||
)
|
||||
|
||||
var JWT_KEY = []byte(global.ServerSettings.Jwt.Secret)
|
||||
|
||||
// Generate token for user
|
||||
// Return: token generated
|
||||
func GenerateToken(claims jwt.MapClaims) string {
|
||||
claims["exp"] = time.Now().Add(15 * 24 * time.Hour).Unix()
|
||||
claims["iat"] = time.Now().Unix()
|
||||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
||||
tokenStr, err := token.SignedString(JWT_KEY)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return tokenStr
|
||||
}
|
||||
|
||||
// Renew user's token
|
||||
// tokenStr: user request token
|
||||
// Return:
|
||||
// BlankString: token is invalid or token is expired out of allowed time;
|
||||
// OldToken: token is not need to renew;
|
||||
// NewToekn: token is renew;
|
||||
func RenewToken(tokenStr string) string {
|
||||
token, err := jwt.Parse(tokenStr, func(t *jwt.Token) (interface{}, error) {
|
||||
return JWT_KEY, nil
|
||||
})
|
||||
|
||||
// Token is invalid
|
||||
switch err.(*jwt.ValidationError).Errors {
|
||||
case jwt.ValidationErrorSignatureInvalid:
|
||||
return ""
|
||||
case jwt.ValidationErrorIssuedAt:
|
||||
return ""
|
||||
}
|
||||
|
||||
claims := token.Claims.(jwt.MapClaims)
|
||||
expireAt := time.Unix(int64(claims["exp"].(float64)), 0)
|
||||
expireDuration := expireAt.Sub(time.Now())
|
||||
|
||||
// Token is out of allow expire duration
|
||||
if expireDuration.Hours() < float64(-global.ServerSettings.Jwt.RenewExpireDays*24) {
|
||||
return ""
|
||||
}
|
||||
// Token not need renew
|
||||
if expireDuration.Hours() > float64(global.ServerSettings.Jwt.RenewAheadDays*24) {
|
||||
return tokenStr
|
||||
}
|
||||
fmt.Println(expireDuration)
|
||||
|
||||
claims["exp"] = time.Now().Add(15 * 24 * time.Hour).Unix()
|
||||
token = jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
||||
tokenStr, err = token.SignedString(JWT_KEY)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return tokenStr
|
||||
}
|
||||
Reference in New Issue
Block a user