package middleware

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/go-admin-team/go-admin-core/sdk/pkg/response"
	"go-admin/common/utils"
	"strconv"
	"strings"
)

// JWTAuthMiddleware 基于JWT的认证中间件
func JWTAuthMiddleware() func(c *gin.Context) {
	return func(c *gin.Context) {
		//ip := exnet.ClientPublicIP(c.Request)
		//if ip == "" {
		//	ip = exnet.ClientIP(c.Request)
		//}
		//if ip != viper.GetString("white_ip.ip") {
		//	utils.ResponseErrorWithMsg(c, utils.CodeInvalidToken, "没有请求权限")
		//	c.Abort()
		//	return
		//}
		//客户端携带Token有三种方式 1.放在请求头 2.放在请求体 3.放在URI
		authHeader := c.Request.Header.Get("Authorization")
		if authHeader == "" {
			response.OK(c, 401, "请求头缺少Auth Token")
			c.Abort()
			return
		}
		// 按空格分割
		parts := strings.SplitN(authHeader, " ", 2)
		if !(len(parts) == 2 && parts[0] == "Bearer") {
			response.OK(c, 402, "请求头中auth格式有误")
			c.Abort()
			return
		}
		// parts[1]是获取到的tokenString，我们使用之前定义好的解析JWT的函数来解析它
		mc, err := utils.ParseToken(parts[1])
		if err != nil {
			response.OK(c, 403, "invalid JWT token")
			c.Abort()
			return
		}
		c.Set("userId", mc.UserId)
		fmt.Println("token:" + parts[1] + "======userid:" + strconv.FormatInt(mc.UserId, 10))
		c.Next()
	}
}
