package middleware

import (
	"github.com/gin-gonic/gin"
	"iot_manager_service/util/cache"
	"iot_manager_service/util/common"
	"iot_manager_service/util/token"
	"net/http"
	"strings"
)

// 验证token令牌的中间件
func AuthMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		//如果包含路径/login则放行，其余的都要进行token认证
		if strings.Contains(c.Request.RequestURI, "/login") ||
			strings.Contains(c.Request.RequestURI, "/getpublicKey") {
			c.Next()
			return
		}
		// 从请求头中获取token
		tokeString := c.GetHeader("Authorization")
		if tokeString == "" {
			c.JSON(http.StatusOK, common.ParamsInvalidResponse("Authorization不能为空", nil))
			c.Abort()
			return
		}
		//解析token
		claims, err := token.JwtClaims.ParseJwtToken(tokeString)
		if err != nil {
			c.JSON(http.StatusOK, common.ParamsInvalidResponse("Authorization解析错误", nil))
			c.Abort()
			return
		}
		//判断是不是最新一次的token，只有最新的有效，否则无效，不放行
		redis_uuid, err := cache.GetToken(claims.ID)
		if redis_uuid != claims.UUID || redis_uuid == "" || err != nil {
			c.JSON(http.StatusOK, common.ParamsInvalidResponse("Authorization失效", nil))
			c.Abort()
			return
		}
		c.Next()
	}
}
