63c12a2f44
eula support * eula support * docs
73 lines
2.3 KiB
Go
73 lines
2.3 KiB
Go
package cognitoauth
|
|
|
|
import (
|
|
"os"
|
|
"strings"
|
|
|
|
"github.com/labstack/echo/v4"
|
|
)
|
|
|
|
// TestUserMiddleware injects test user identity from headers when DISABLE_AUTH=true.
|
|
//
|
|
// This middleware enables testing of user-authenticated endpoints without real JWT
|
|
// authentication. It only activates when the DISABLE_AUTH environment variable is
|
|
// set to "true". In production (DISABLE_AUTH=false or unset), this middleware does
|
|
// nothing and passes requests through unchanged.
|
|
//
|
|
// When active, it checks for the X-Test-User-Subject header. If present, it injects
|
|
// user identity into the request context, allowing handlers to retrieve user info
|
|
// via GetUserSubject() and GetUserInfo() as if a real JWT had been validated.
|
|
//
|
|
// Headers:
|
|
// - X-Test-User-Subject: The user's subject ID (required for injection)
|
|
// - X-Test-User-Email: The user's email (optional, defaults to <subject>@test.local)
|
|
//
|
|
// Usage in test scripts:
|
|
//
|
|
// curl -X GET http://localhost:8080/eula/status \
|
|
// -H "X-Test-User-Subject: test-user-123" \
|
|
// -H "X-Test-User-Email: testuser@example.com"
|
|
//
|
|
// This middleware should be registered early in the middleware chain so that
|
|
// subsequent handlers and middleware can access the injected user context.
|
|
//
|
|
// Returns:
|
|
// - echo.MiddlewareFunc: Middleware that conditionally injects test user identity
|
|
func TestUserMiddleware() echo.MiddlewareFunc {
|
|
return func(next echo.HandlerFunc) echo.HandlerFunc {
|
|
return func(c echo.Context) error {
|
|
// Only active when DISABLE_AUTH=true (test mode)
|
|
disableAuth := os.Getenv("DISABLE_AUTH")
|
|
if strings.ToLower(disableAuth) != "true" {
|
|
return next(c)
|
|
}
|
|
|
|
// Check for test user header
|
|
subject := c.Request().Header.Get("X-Test-User-Subject")
|
|
if subject == "" {
|
|
// No test user header, continue normally
|
|
// (admin endpoints will use system user via their own logic)
|
|
return next(c)
|
|
}
|
|
|
|
// Get email from header or generate default
|
|
email := c.Request().Header.Get("X-Test-User-Email")
|
|
if email == "" {
|
|
email = subject + "@test.local"
|
|
}
|
|
|
|
// Inject user context (same structure as real auth middleware)
|
|
c.Set("user_claims", map[string]any{
|
|
"sub": subject,
|
|
"email": email,
|
|
})
|
|
c.Set("user_info", UserInfo{
|
|
Email: email,
|
|
Username: subject,
|
|
})
|
|
|
|
return next(c)
|
|
}
|
|
}
|
|
}
|