package handlers import ( "github.com/spf13/viper" "net/http" "passport/app/models" "passport/pkg/ierr" "passport/pkg/jwt" "time" "github.com/gin-gonic/gin" ) var Cors = func(c *gin.Context) { method := c.Request.Method c.Header("Access-Control-Allow-Origin", "*") c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, UPDATE") c.Header("Access-Control-Allow-Headers", "*") if method == "OPTIONS" { c.AbortWithStatus(http.StatusNoContent) } c.Next() } func AuthToken() gin.HandlerFunc { //这里不管是什么身份只要登录了就可以 return func(c *gin.Context) { token := c.GetHeader("shopManageToken") if token == "" { token = c.Query("shopManageToken") } if token == "" { ResponseErr(c, ierr.NewIError(ierr.NotAllowed, "need login")) c.Abort() return } res, err := jwt.ParseToken(token, viper.GetString("token_secret")) if err != nil { ResponseErr(c, ierr.NewIError(ierr.NotAllowed, err.Error())) c.Abort() return } if res.Expire < time.Now().Unix() { ResponseErr(c, ierr.NewIError(ierr.TokenExpire, "token expire")) c.Abort() return } c.Set("uid", res.UserId) c.Next() } } func AdminToken() gin.HandlerFunc { return func(c *gin.Context) { token := c.GetHeader("shopManageToken") if token == "" { token = c.Query("shopManageToken") } if token == "" { ResponseErr(c, ierr.NewIError(ierr.NotAllowed, "need login")) c.Abort() return } res, err := jwt.ParseToken(token, viper.GetString("token_secret")) if err != nil { ResponseErr(c, ierr.NewIError(ierr.NotAllowed, err.Error())) c.Abort() return } if res.Expire < time.Now().Unix() { ResponseErr(c, ierr.NewIError(ierr.TokenExpire, "token expire")) c.Abort() return } if res.Role != models.RoleAdmin { ResponseErr(c, ierr.NewIError(ierr.NotAllowed, "have no admin access")) c.Abort() return } c.Set("uid", res.UserId) c.Next() } } func MerchantToken() gin.HandlerFunc { return func(c *gin.Context) { token := c.GetHeader("shopManageToken") if token == "" { token = c.Query("shopManageToken") } if token == "" { ResponseErr(c, ierr.NewIError(ierr.NotAllowed, "need login")) c.Abort() return } res, err := jwt.ParseToken(token, viper.GetString("token_secret")) if err != nil { ResponseErr(c, ierr.NewIError(ierr.NotAllowed, err.Error())) c.Abort() return } if res.Expire < time.Now().Unix() { ResponseErr(c, ierr.NewIError(ierr.TokenExpire, "token expire")) c.Abort() return } if res.Role != models.RoleMerchant { ResponseErr(c, ierr.NewIError(ierr.NotAllowed, "have no merchant access")) c.Abort() return } c.Set("uid", res.UserId) c.Next() } }