39 lines
1.3 KiB
Go
39 lines
1.3 KiB
Go
|
|
package authmw
|
||
|
|
|
||
|
|
import (
|
||
|
|
"net/http"
|
||
|
|
|
||
|
|
"code.nochebuena.dev/einherjar/contracts/security"
|
||
|
|
)
|
||
|
|
|
||
|
|
// EnrichOpt configures [EnrichmentMiddleware] behaviour.
|
||
|
|
type EnrichOpt func(*enrichConfig)
|
||
|
|
|
||
|
|
// WithTenantHeader reads the TenantID from the named request header and
|
||
|
|
// applies it to the Identity inside the bag via [security.Identity.WithTenant].
|
||
|
|
//
|
||
|
|
// Equivalent to registering a [BagEnricher] that calls
|
||
|
|
// bag.WithIdentity(bag.Identity().WithTenant(r.Header.Get(header))).
|
||
|
|
// Use for multi-tenant deployments where the tenant is identified per request.
|
||
|
|
func WithTenantHeader(header string) EnrichOpt {
|
||
|
|
return WithBagEnricher(func(bag security.SecurityBag, r *http.Request) security.SecurityBag {
|
||
|
|
if tenantID := r.Header.Get(header); tenantID != "" {
|
||
|
|
return bag.WithIdentity(bag.Identity().WithTenant(tenantID))
|
||
|
|
}
|
||
|
|
return bag
|
||
|
|
})
|
||
|
|
}
|
||
|
|
|
||
|
|
// WithBagEnricher appends fn to the enrichment chain.
|
||
|
|
// Enrichers run in registration order after the base Identity is built.
|
||
|
|
// Each enricher receives the bag returned by the previous one.
|
||
|
|
//
|
||
|
|
// Use this for any enrichment that does not fit [WithTenantHeader]:
|
||
|
|
// attaching hardware IDs, grant codes, or any attribute that downstream
|
||
|
|
// permission providers need to read from the bag.
|
||
|
|
func WithBagEnricher(fn BagEnricher) EnrichOpt {
|
||
|
|
return func(c *enrichConfig) {
|
||
|
|
c.enrichers = append(c.enrichers, fn)
|
||
|
|
}
|
||
|
|
}
|