package apiinterceptor

import (
	"net/http"
	"strings"

	"github.com/gin-gonic/gin"
	"github.com/pingcap/log"
	"github.com/tidbcloud/observability/pkg/common/awsauth"
	"github.com/tidbcloud/observability/pkg/common/constants"
	"go.uber.org/zap"
)

func ServiceAuthentication(c *gin.Context) {
	bearerTokenStr := c.GetHeader(constants.AuthorizationHeader)
	token := strings.TrimSpace(bearerTokenStr[len(constants.BearerPrefix):])

	err := awsauth.ValidateStsToken(c, token)
	if err != nil {
		log.Error("validate sts token failed", zap.Error(err), zap.String("Path", c.Request.URL.Path))
		c.AbortWithStatusJSON(http.StatusUnauthorized, err.Error())
		return
	}

	c.Next()
}
