package router import ( "gas-cylinder-api/app/admin/controller" "gas-cylinder-api/app/admin/model" "github.com/dgrijalva/jwt-go" "github.com/gin-gonic/gin" "net/http" "strings" "time" ) var ( appletRouterCheck = make([]func(v1 *gin.RouterGroup, authMiddleware gin.HandlerFunc), 0) ) func init() { appletRouterCheck = append(appletRouterCheck, AppletCustomerRouter) } func AppletCunJWTMiddleware() gin.HandlerFunc { return func(c *gin.Context) { tokenString := c.GetHeader("Authorization") if tokenString == "" { c.JSON(http.StatusUnauthorized, gin.H{ "code": 401, "msg": "Unauthorized", }) c.Abort() return } parts := strings.SplitN(tokenString, " ", 2) if !(len(parts) == 2 && parts[0] == "Bearer") { c.JSON(http.StatusOK, gin.H{ "code": 401, "msg": "请求头中auth格式有误", }) c.Abort() return } // 解析token token, err := jwt.ParseWithClaims(parts[1], &model.CustomerClaims{}, func(token *jwt.Token) (i interface{}, err error) { return model.AppletCustomerSecret, nil }) if err != nil || !token.Valid { if err.(*jwt.ValidationError).Errors != jwt.ValidationErrorExpired { c.JSON(http.StatusUnauthorized, gin.H{ "code": 401, "msg": "Unauthorized", }) c.Abort() return } } claims, ok := token.Claims.(*model.CustomerClaims) if !ok { c.JSON(http.StatusUnauthorized, gin.H{ "code": 401, "msg": "Unauthorized", }) c.Abort() return } if claims.ExpiresAt < time.Now().Unix() { if claims.ExpiresAt > time.Now().Add(-2*time.Hour).Unix() { c.JSON(http.StatusUnauthorized, gin.H{ "code": 6401, "msg": "Token is expired", }) c.Abort() return } c.JSON(http.StatusUnauthorized, gin.H{ "code": 6401, "msg": "Token is expired", }) c.Abort() return } c.Set("customer_id", claims.CustomerId) c.Next() } } func AppletCustomerRouterInit(v1 *gin.RouterGroup) { cont := controller.AppletCustomerController{} r := v1.Group("/api/applet") { r.POST("/login", cont.Login) r.POST("/register", cont.Register) r.GET("/refresh", cont.Refresh) } for _, f := range appletRouterCheck { f(r, AppletCunJWTMiddleware()) } } func AppletCustomerRouter(v1 *gin.RouterGroup, authMiddleware gin.HandlerFunc) { cont := controller.AppletCustomerController{} r := v1.Group("").Use(authMiddleware) { r.GET("/profile", cont.GetProfile) r.PUT("/customer-info", cont.UpdateCustomerInfo) r.PUT("/pwd", cont.UpdatePwd) r.GET("/order", cont.GetOrderPage) r.POST("/order", cont.OrderInsert) r.PUT("/order", cont.OrderUpdate) r.POST("/order/cancel", cont.OrderCancel) r.GET("/store", cont.StoreList) r.GET("/goods", cont.GetGoodsPage) r.GET("/gas-cylinder-spec", cont.GetGasCylinderSpecPage) } }