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, "/websocket") ||
			strings.Contains(c.Request.RequestURI, "/getPublicKey") {
			c.Next()
			return
		}
		// 从请求头中获取token
		tokenString := c.GetHeader("Authorization")
		if tokenString == "" {
			c.JSON(http.StatusOK, common.ParamsInvalidResponse("验证不能为空", nil))
			c.Abort()
			return
		}
		//解析token
		claims, err := token.JwtClaims.ParseJwtToken(tokenString)
		//过期或者无效
		if err != nil {
			c.JSON(http.StatusUnauthorized, common.StatusUnauthorized("登录过期，请重新登录", nil))
			c.Abort()
			return
		}
		user, _ := cache.GetNowSysUser(claims.ID)
		if user.ID == 0 {
			c.JSON(http.StatusUnauthorized, common.StatusUnauthorized("请先登录！", nil))
			c.Abort()
			return
		}
		c.Next()
	}
}
