Skip to content

Commit

Permalink
feat: 增加auth/renew接口,支持刷新jwt
Browse files Browse the repository at this point in the history
- context中增加token的过期时间戳
- 增加auth/renew接口,刷新登录态token
  • Loading branch information
jorben committed Jul 3, 2024
1 parent be33edf commit b94b8b8
Show file tree
Hide file tree
Showing 4 changed files with 46 additions and 6 deletions.
2 changes: 2 additions & 0 deletions common/errs/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ const (
ErrAuthLoginFailed = -10004 // 登录失败
ErrAuthNoLogin = -10005 // 未登录
ErrAuthUnauthorized = -10006 // 未授权
ErrAuthUnexpired = -10007 // 未过期
)

// 定义错误码对应的错误描述
Expand All @@ -21,6 +22,7 @@ var errorMsg = map[int]string{
ErrAuthLoginFailed: "登录/注册失败,请稍后重试",
ErrAuthNoLogin: "未登录或登录态已过期",
ErrAuthUnauthorized: "未授权或权限不足",
ErrAuthUnexpired: "刷新登录态失败,当前登录态还有足够长的有效期",
}

// GetErrorMsg 获取错误码对应的错误描述
Expand Down
7 changes: 6 additions & 1 deletion middleware/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,19 @@ import (
func Auth() gin.HandlerFunc {
return func(ctx *gin.Context) {
var userId string
var expiresAt int64
c := context.CustomContext{Context: ctx}
tokenString := ctx.GetHeader("X-Token")
authService := service.NewAuthService(ctx)

if len(tokenString) > 0 {
userId, _ = authService.VerifyJwtString(tokenString)
if token, err := authService.VerifyJwtString(tokenString); err == nil {
userId = token.UserId
expiresAt = token.ExpiresAt
}
}
ctx.Set("UserId", userId)
ctx.Set("ExpiresAt", expiresAt)

// 校验权限
path := ctx.Request.URL.Path
Expand Down
29 changes: 29 additions & 0 deletions router/api/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ import (
"league/provider/auth"
"league/service"
"net/http"
"strconv"
"time"
)

// AuthProvider 第三方登录渠道接口
Expand Down Expand Up @@ -95,5 +97,32 @@ func AuthCallback(ctx *gin.Context) {

// AuthRenew 续期JWT
func AuthRenew(ctx *gin.Context) {
c := context.CustomContext{Context: ctx}

strUserId := ctx.Value("UserId").(string)
userId, err := strconv.Atoi(strUserId)
if err != nil {
c.CJSON(errs.ErrAuthNoLogin)
return
}
expiresAt, ok := ctx.Value("ExpiresAt").(int64)
if !ok {
expiresAt = 0
}

now := time.Now()
if expiresAt-now.Unix() > 1*60*60 {
// 距离过期时间>1小时 不予刷新
c.CJSON(errs.ErrAuthUnexpired)
return
}

authService := service.NewAuthService(ctx)
token, err := authService.SignJwtString(uint(userId))
if err != nil {
c.CJSON(errs.ErrAuthLoginFailed, "刷新token失败,请稍后重试")
return
}
c.CJSON(errs.Success, token)

}
14 changes: 9 additions & 5 deletions service/authservice.go
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ func (a *AuthService) SignJwtString(id uint) (*AuthToken, error) {
token := jwt.NewWithClaims(jwt.SigningMethodHS384, claims)
sign, err := token.SignedString(a.signKey)
if err != nil {
log.Errorf(a.Ctx, "Jwt SignedString failed, err: %s", err.Error())
log.Infof(a.Ctx, "Jwt SignedString failed, err: %s", err.Error())
return nil, err
}
return &AuthToken{
Expand All @@ -100,20 +100,24 @@ func (a *AuthService) SignJwtString(id uint) (*AuthToken, error) {
}

// VerifyJwtString 校验JWT
func (a *AuthService) VerifyJwtString(s string) (string, error) {
func (a *AuthService) VerifyJwtString(s string) (*AuthToken, error) {

token, err := jwt.ParseWithClaims(s, &jwt.RegisteredClaims{}, func(token *jwt.Token) (interface{}, error) {
return a.signKey, nil
})
if err != nil {
log.Errorf(a.Ctx, "Jwt parse failed, err: %s", err.Error())
return "", err
return nil, err
} else if claims, ok := token.Claims.(*jwt.RegisteredClaims); ok {
log.Debugf(a.Ctx, "Check login passed, UserId: %s", claims.ID)
return claims.ID, nil
return &AuthToken{
UserId: claims.ID,
ExpiresAt: claims.ExpiresAt.Unix(),
NotBefore: claims.NotBefore.Unix(),
}, nil
} else {
log.Errorf(a.Ctx, "Unknown claims type, token: %s", s)
return "", errors.New("unknown claims type")
return nil, errors.New("unknown claims type")
}
}

Expand Down

0 comments on commit b94b8b8

Please sign in to comment.