internal/auth: add TenantChannelMiddleware

Extracts the tenant from the JWT and sets it in the request context.
This commit is contained in:
Sanne Raymaekers 2023-06-17 17:39:27 +02:00
parent bec17b6d47
commit 0f946e1c9e
4 changed files with 50 additions and 11 deletions

View file

@ -0,0 +1,29 @@
package auth
import (
"errors"
"fmt"
"github.com/labstack/echo/v4"
)
const TenantCtxKey string = "tenant"
func TenantChannelMiddleware(tenantProviderFields []string, onFail error) func(next echo.HandlerFunc) echo.HandlerFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(ctx echo.Context) error {
tenant, err := GetFromClaims(ctx.Request().Context(), tenantProviderFields)
// Allowlisted paths won't have a token
if err != nil && !errors.Is(err, NoJWTError) {
return onFail
}
// prefix the tenant to prevent collisions if support for specifying channels in a request is ever added
if tenant != "" {
ctx.Set(TenantCtxKey, fmt.Sprintf("org-%s", tenant))
}
return next(ctx)
}
}
}