From 72ef5c92c46fe91612f2a01dc242f4a5de2db674 Mon Sep 17 00:00:00 2001 From: fallen-angle <1853633282@qq.com> Date: Sat, 12 Feb 2022 16:32:34 +0800 Subject: [PATCH] feat: jwt middleware --- .gitignore | 1 + handler/article.go | 5 ++++- middleware/auth.go | 29 +++++++++++++++++++++++++++++ models/article.go | 2 +- models/user.go | 15 +++++++++++++++ router/article.go | 6 +++--- router/router.go | 28 ++++++++++++---------------- router/statistics.go | 6 +++--- utils/jwt.go | 20 +++++++++++--------- utils/response.go | 4 ++++ 10 files changed, 83 insertions(+), 33 deletions(-) create mode 100644 middleware/auth.go create mode 100644 models/user.go diff --git a/.gitignore b/.gitignore index 2bdb3cd..b7dddbc 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ *.log *.release +.idea \ No newline at end of file diff --git a/handler/article.go b/handler/article.go index 681be7b..f61890e 100644 --- a/handler/article.go +++ b/handler/article.go @@ -2,6 +2,7 @@ package handler import ( "fmt" + "nCovTrack-Backend/global" "nCovTrack-Backend/models" "nCovTrack-Backend/utils" @@ -10,8 +11,10 @@ import ( ) func SaveArticleHandler(c *gin.Context) { - var articleSave models.Article + var articleSave models.BackArticle c.ShouldBindJSON(&articleSave) fmt.Println(utils.RenewToken("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2NDMxMDA5MDAsImlhdCI6MTY0MzQyNDkwMH0.L8qNmbHJtV8fiKKxGbkZk3DrKBPdvhie_oFooH5hGOY")) utils.Succ(c, map[string]string{"string": utils.GenerateToken(jwt.MapClaims{})}) + global.Db.First(&articleSave) + fmt.Println(articleSave) } diff --git a/middleware/auth.go b/middleware/auth.go new file mode 100644 index 0000000..61ddab4 --- /dev/null +++ b/middleware/auth.go @@ -0,0 +1,29 @@ +package middleware + +import ( + "github.com/gin-gonic/gin" + "nCovTrack-Backend/utils" + "net/http" +) + +const UNAUTH_MSG = "unauthorized" + +func Auth() gin.HandlerFunc { + return func(c *gin.Context) { + oldToken := c.Request.Header["Token"] + c.Writer.Header().Set("X-Token", "") + if len(oldToken) != 1 || oldToken[0] == "" { + utils.Err(c, http.StatusUnauthorized, http.StatusUnauthorized, UNAUTH_MSG) + c.Abort() + return + } + renewToken := utils.RenewToken(oldToken[0]) + if renewToken == "" { + utils.Err(c, http.StatusUnauthorized, http.StatusUnauthorized, UNAUTH_MSG) + c.Abort() + return + } + c.Writer.Header().Set("X-Token", renewToken) + c.Next() + } +} diff --git a/models/article.go b/models/article.go index 1151d92..77ddab6 100644 --- a/models/article.go +++ b/models/article.go @@ -2,7 +2,7 @@ package models import "time" -type Article struct { +type BackArticle struct { ID int `gorm:"primaryKey;column:id" json:"-"` // 文章id CreateTime time.Time `gorm:"column:create_time" json:"createTime"` // 文章新建时间 CreateUser string `gorm:"column:create_user" json:"createUser"` // 文章创建者id diff --git a/models/user.go b/models/user.go new file mode 100644 index 0000000..b54406d --- /dev/null +++ b/models/user.go @@ -0,0 +1,15 @@ +package models + +import "time" + +type BackUser struct { + ID int `gorm:"primaryKey;column:id" json:"-"` // 用户ID + Username string `gorm:"column:username" json:"username"` // 用户真实姓名 + Password string `gorm:"column:password" json:"password"` // 用户密码 + Role int `gorm:"column:role" json:"role"` // 用户角色 + Email string `gorm:"column:email" json:"email"` // 用户邮箱 + Phone string `gorm:"column:phone" json:"phone"` // 用户手机号码 + Aptitude string `gorm:"column:aptitude" json:"aptitude"` // 用户资质证明(图片URL) + RegisterTime time.Time `gorm:"column:register_time" json:"registerTime"` // 用户注册时间 + Approver int `gorm:"column:approver" json:"approver"` // 注册审核人ID +} diff --git a/router/article.go b/router/article.go index f0dcc8d..1cada66 100644 --- a/router/article.go +++ b/router/article.go @@ -1,12 +1,12 @@ package router import ( - "nCovTrack-Backend/global" + "github.com/gin-gonic/gin" "nCovTrack-Backend/handler" ) -func articleRouter() { - articleRouter := global.RootRouter.Group("/article") +func articlePrivateRouter(router *gin.RouterGroup) { + articleRouter := router.Group("/article") { articleRouter.POST("/save", handler.SaveArticleHandler) } diff --git a/router/router.go b/router/router.go index b5b6c1a..e8e05d8 100644 --- a/router/router.go +++ b/router/router.go @@ -2,25 +2,21 @@ package router import ( "nCovTrack-Backend/global" - "net/http" - "time" - - "github.com/gin-gonic/gin" + "nCovTrack-Backend/middleware" ) func BusiRouter() { - testRouter := global.RootRouter.Group("/test") + publicRouter := global.RootRouter.Group("") + privateRouter := global.RootRouter.Group("") + privateRouter.Use(middleware.Auth()) + + // Public { - testRouter.GET("/count", func(c *gin.Context) { - time.Sleep(800 * time.Millisecond) - c.String(http.StatusOK, "OK") - }) - //testRouter.GET("/test", statistics.GetChinaNCovStatistic()) - //testRouter.GET("/redis", func(c *gin.Context) { - // data := statistics.GetAllProvienceData(statistics.SORT_NOW_CONFIRM) - // Succ(c, data) - //}) + statisticRouter(publicRouter) + } + + // Private + { + articlePrivateRouter(privateRouter) } - statisticRouter() - articleRouter() } diff --git a/router/statistics.go b/router/statistics.go index 718309f..b4a73a1 100644 --- a/router/statistics.go +++ b/router/statistics.go @@ -1,12 +1,12 @@ package router import ( - "nCovTrack-Backend/global" + "github.com/gin-gonic/gin" "nCovTrack-Backend/handler" ) -func statisticRouter() { - statisticsRouter := global.RootRouter.Group("/statistics") +func statisticRouter(router *gin.RouterGroup) { + statisticsRouter := router.Group("/statistics") { statisticsRouter.GET("/provience/:sort", handler.ProvienceDataHandler) statisticsRouter.GET("/city/:sort", handler.CityDataHandler) diff --git a/utils/jwt.go b/utils/jwt.go index fd5db7e..f68bc4f 100644 --- a/utils/jwt.go +++ b/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 diff --git a/utils/response.go b/utils/response.go index 00a00c8..d92f2b8 100644 --- a/utils/response.go +++ b/utils/response.go @@ -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}) +}