package middleware

import (
	"github.com/gogf/gf/v2/net/ghttp"
	"yx-dataset-server/app/errors"
	"yx-dataset-server/library/auth"
	"yx-dataset-server/library/gplus"
	"yx-dataset-server/library/utils"
	"yx-dataset-server/router/api/controllers"
)

func UserAuthMiddleware(auth auth.Auther, skippers ...SkipperFunc) ghttp.HandlerFunc {
	return func(r *ghttp.Request) {
		if len(skippers) > 0 && skippers[0](r) {
			r.Middleware.Next()
			return
		}
		var userId string
		if t := gplus.GetToken(r); t != "" {
			id, err := auth.ParseUserID(t)
			if err != nil {
				controllers.ResError(r, err)
			}
			userId = id
		}
		if userId != "" {
			gplus.SetUserId(r, userId)
		}
		if userId == "" {
			if utils.GetConfig("common.RunMode").String() == "debug" {
				gplus.SetUserId(r, utils.GetConfig("root.user_name").String())
				r.Middleware.Next()
				return
			}
			controllers.ResError(r, errors.ErrNoPerm)
		}
		r.Middleware.Next()
	}
}
