服务器端Token凭证的动态刷新
middleware
package middleware
import (
"github.com/gin-gonic/gin"
"github.com/lijinghuatongxue/quick-server/model"
"github.com/lijinghuatongxue/quick-server/pkg/e"
"github.com/sirupsen/logrus"
"net/http"
"time"
)
// 动态刷新用户Token有效期,1个小时
func UserTokenLifeExtension() gin.HandlerFunc {
return func(c *gin.Context) {
// get token
tokenStr := c.Request.Header.Get("token")
if tokenStr == "" {
tokenStr = c.Request.Header.Get("Authorization")
//logrus.Error(tokenStr)
if tokenStr == "" {
c.JSON(http.StatusUnauthorized, gin.H{
"code": e.INVALID_PARAMS,
"msg": e.GetMsg(400),
})
c.Abort()
return
}
}
if c.Request.Method == "OPTIONS" {
c.AbortWithStatus(204)
return
}
IsExtensionUserToken, _ := model.InitRedis().ExpireAt(ctx, tokenStr, time.Now().Add(time.Minute*60)).Result()
if IsExtensionUserToken != true {
logrus.Errorf("[Token 有效期重置] | 失败!|%s", tokenStr)
c.JSON(500, gin.H{
"code": e.ERR_USER_TOKEN_LIFE_EXTENSION,
"data": "",
"msg": e.GetMsg(e.ERR_USER_TOKEN_LIFE_EXTENSION),
})
return
}
c.Next()
}
}
router.go
除去用户登陆、登出动作之外,其余的api每次访问,都重新刷新Token有效期
register_login := r.Group("/api")
{
register_login.POST("/logout", api.TokenAuthMiddleware())
register_login.POST("/register", api.RegisterUser)
register_login.POST("/login", api.Login)
}
register_user := r.Group("/api", middleware.UserTokenLifeExtension())
{
register_user.GET("/GetUser", middleware.TokenAuthMiddleware(), User.GetUserAll)
register_user.POST("/DelUser", middleware.TokenAuthMiddleware(), api.DelUser)
register_user.POST("/ResetUserPasswd", middleware.TokenAuthMiddleware(), api.ResetUserPasswd)
}
api := r.Group("/api", middleware.UserTokenLifeExtension())
{
api.POST("/upload", middleware.TokenAuthMiddleware(), src.Upload)
api.GET("/GetUploadInfo", middleware.TokenAuthMiddleware(), src.GetUploadInfo)
api.POST("/DelUploadInfo", middleware.TokenAuthMiddleware(), src.DelUploadInfo)
}