package middleware

import (
	"strings"

	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	"nn.daxia.dev/model"
)

func Auth() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		var err error

		if ctx.Request.Method == "OPTIONS" {
			ctx.Next()
			return
		}

		path := ctx.Request.URL.Path
		if strings.HasPrefix(path, "/connect") {
			ctx.Next()
			return
		}

		userToken := ctx.Request.Header.Get("x-token")
		once := ctx.Request.Header.Get("x-once")
		if userToken == "" || once == "" {
			logrus.Error("参数错误:", "once:", once, " token:", userToken)
			ctx.AbortWithStatus(500)
			return
		}

		userModel := model.User{}
		isValid, err := userModel.TokenIsValid(userToken)
		if err != nil {
			logrus.Error(err)
			ctx.AbortWithStatus(500)
			return
		}

		if !isValid {
			ctx.JSON(200, "用户被禁用")
			ctx.AbortWithStatus(500)
			return
		}

		ctx.Set("req_ctx", map[string]interface{}{
			"userModel": userModel,
			"once":      once,
		})

		ctx.Next()
	}
}
