123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115 |
- package handlers
- import (
- "github.com/spf13/viper"
- "net/http"
- "shopperthree_manage_v2/app/models"
- "shopperthree_manage_v2/pkg/ierr"
- "shopperthree_manage_v2/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()
- }
- }
|