package middleware

import (
	"DataShare/dao"
	"github.com/gin-gonic/gin"
	"net/http"
)

func TokenAuthMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		err := TokenValid(c.Request)
		if err != nil {
			c.JSON(http.StatusUnauthorized, "unauthorized")
			c.Abort()
			return
		}
		metadata, err := ExtractTokenMetadata(c.Request)
		if err != nil {
			c.JSON(http.StatusUnauthorized, "unauthorized")
			c.Abort()
			return
		}

		uuidInfo ,err := dao.FetchAuth(metadata.TokenUuid)
		if len(uuidInfo)<=0{
			c.JSON(http.StatusUnauthorized, "unauthorized")
			c.Abort()
			return
		}

		ret,_,err := dao.Empower_GetInstance().GetLiceneseLeftDays()
		if err != nil {
			c.JSON(http.StatusUnauthorized, "unauthorized failed:"+err.Error())
			c.Abort()
			return
		}
		if ret == false {
			c.JSON(http.StatusUnauthorized, "unauthorized expired:")
			c.Abort()
			return
		}
		c.Next()
	}
}
