feat: jwt middleware
This commit is contained in:
20
utils/jwt.go
20
utils/jwt.go
@@ -10,7 +10,7 @@ import (
|
||||
|
||||
var JWT_KEY = []byte(global.ServerSettings.Jwt.Secret)
|
||||
|
||||
// Generate token for user
|
||||
// GenerateToken Generate token for user
|
||||
// Return: token generated
|
||||
func GenerateToken(claims jwt.MapClaims) string {
|
||||
claims["exp"] = time.Now().Add(15 * 24 * time.Hour).Unix()
|
||||
@@ -23,23 +23,25 @@ func GenerateToken(claims jwt.MapClaims) string {
|
||||
return tokenStr
|
||||
}
|
||||
|
||||
// Renew user's token
|
||||
// RenewToken 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;
|
||||
// NewToken: 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 ""
|
||||
if err != nil {
|
||||
switch err.(*jwt.ValidationError).Errors {
|
||||
case jwt.ValidationErrorSignatureInvalid:
|
||||
return ""
|
||||
case jwt.ValidationErrorIssuedAt:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
claims := token.Claims.(jwt.MapClaims)
|
||||
@@ -47,7 +49,7 @@ func RenewToken(tokenStr string) string {
|
||||
expireDuration := expireAt.Sub(time.Now())
|
||||
|
||||
// Token is out of allow expire duration
|
||||
if expireDuration.Hours() < float64(-global.ServerSettings.Jwt.RenewExpireDays*24) {
|
||||
if expireDuration.Hours() < -float64(global.ServerSettings.Jwt.RenewExpireDays*24) {
|
||||
return ""
|
||||
}
|
||||
// Token not need renew
|
||||
|
||||
@@ -18,3 +18,7 @@ func Error(c *gin.Context, status int, code int, msg interface{}, data interface
|
||||
func Succ(c *gin.Context, data interface{}) {
|
||||
Success(c, http.StatusOK, "success", data)
|
||||
}
|
||||
|
||||
func Err(c *gin.Context, status int, code int, msg interface{}) {
|
||||
c.JSON(status, models.GinResponse{Code: code, Msg: msg})
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user