38 lines
890 B
Go
38 lines
890 B
Go
|
|
package middleware
|
||
|
|
|
||
|
|
import (
|
||
|
|
"context"
|
||
|
|
|
||
|
|
"github.com/gin-gonic/gin"
|
||
|
|
|
||
|
|
"github.com/geo-platform/tenant-api/internal/shared/auth"
|
||
|
|
"github.com/geo-platform/tenant-api/internal/shared/response"
|
||
|
|
)
|
||
|
|
|
||
|
|
type tenantIDKey struct{}
|
||
|
|
|
||
|
|
func TenantScope() gin.HandlerFunc {
|
||
|
|
return func(c *gin.Context) {
|
||
|
|
actor, ok := auth.ActorFromCtx(c.Request.Context())
|
||
|
|
if !ok || actor.TenantID == 0 {
|
||
|
|
response.Error(c, response.ErrUnauthorized(40104, "tenant_scope_missing", "tenant context is required"))
|
||
|
|
c.Abort()
|
||
|
|
return
|
||
|
|
}
|
||
|
|
ctx := WithTenantID(c.Request.Context(), actor.TenantID)
|
||
|
|
c.Request = c.Request.WithContext(ctx)
|
||
|
|
c.Next()
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
func WithTenantID(ctx context.Context, tenantID int64) context.Context {
|
||
|
|
return context.WithValue(ctx, tenantIDKey{}, tenantID)
|
||
|
|
}
|
||
|
|
|
||
|
|
func TenantIDFromCtx(ctx context.Context) int64 {
|
||
|
|
if v, ok := ctx.Value(tenantIDKey{}).(int64); ok {
|
||
|
|
return v
|
||
|
|
}
|
||
|
|
return 0
|
||
|
|
}
|