package middleware

import (
	"bytes"
	"fmt"
	"gin-vue-admin/model/response"
	"gin-vue-admin/utils"
	"github.com/gin-gonic/gin"
	"io/ioutil"
	"strconv"
)

var NoPrintCap = []string{
	"/mobile/upload",
}

func NoJWTAuth() gin.HandlerFunc {
	return func(c *gin.Context) {
		// 我们这里jwt鉴权取头部信息 x-token 登录时回返回token信息 这里前端需要把token存储到cookie或者本地localStorage中 不过需要跟后端协商过期时间 可以约定刷新令牌或者重新登录
		token := c.Request.Header.Get("x-token")
		if token != "" {
			j := NewJWT()
			// parseToken 解析token包含的信息
			claims, err := j.ParseToken(token)
			if err == nil {
				c.Set("claims", claims)
			} else {
				if err == TokenExpired {
					response.FailWithDetailedCode(8, gin.H{"reload": true}, "授权已过期", c)
					c.Abort()
					return
				}
				response.FailWithDetailed(gin.H{"reload": true}, err.Error(), c)
				c.Abort()
				return
			}

			if !utils.InArray(c.Request.URL.Path, NoPrintCap) {
				body, _ := ioutil.ReadAll(c.Request.Body)
				fmt.Println(string(body))
				//把读过的字节流重新放到body
				c.Request.Body = ioutil.NopCloser(bytes.NewBuffer(body))
			}
			fmt.Println("======userid:" + strconv.Itoa(int(claims.ID)))
		}
		c.Next()
	}
}
