Files
tm_back/internal/document_scraper/middleware.go
T
2026-04-28 16:53:36 +03:30

36 lines
967 B
Go

package document_scraper
import (
"strings"
"tm/pkg/response"
"github.com/labstack/echo/v4"
)
// APIKeyMiddleware validates the API key for service-to-service authentication
func APIKeyMiddleware(apiKey string) echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
// Extract API key from X-API-Key header
apiKeyHeader := c.Request().Header.Get("X-API-Key")
if apiKeyHeader == "" {
// Also check Authorization header with "ApiKey <key>" format
authHeader := c.Request().Header.Get("Authorization")
if strings.HasPrefix(authHeader, "ApiKey ") {
apiKeyHeader = strings.TrimPrefix(authHeader, "ApiKey ")
}
}
if apiKeyHeader == "" {
return response.Unauthorized(c, "API key required. Use X-API-Key header or Authorization: ApiKey <key>")
}
if apiKeyHeader != apiKey {
return response.Unauthorized(c, "Invalid API key")
}
return next(c)
}
}
}