package middleware

import (
	"gadmin/utility/serializer"
	"gadmin/utility/token"
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
)

// 路由白名单
var whitelist = []string{
	"/api/gm/userRoles",
}

// Token 验证token
func Token() gin.HandlerFunc {
	return func(c *gin.Context) {
		if isWhite(c.Request.URL.Path) {
			c.Next()
			return
		}

		t := token.GetAuthorization(c)
		if t == "" {
			c.JSON(200, serializer.CheckLogin())
			c.Abort()
			return
		}
		claims, err := token.ParseToken(t)
		if err != nil {
			logrus.Warningf("middleware token.ParseToken:%+v", err.Error())
			//c.JSON(200, serializer.Err(consts.CodeCheckLogin, err.Error(), nil)) // 会导致无法重新登录

			c.JSON(200, serializer.CheckLogin())
			c.Abort()
			return
		}

		//if os.Getenv("GIN_MODE") == "release" && claims.UserName == "mojun" {
		//	c.JSON(200, serializer.CheckLogin())
		//	c.Abort()
		//	return
		//}

		c.Set("user", claims)
		c.Next()
		return
	}
}

func isWhite(path string) bool {
	for _, v := range whitelist {
		if path == v {
			return true
		}
	}
	return false
}
