2
0

namespace.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. package authz
  2. import (
  3. "context"
  4. "net/http"
  5. "strings"
  6. "github.com/porter-dev/porter/api/server/shared/config"
  7. "github.com/porter-dev/porter/api/types"
  8. )
  9. type NamespaceScopedFactory struct {
  10. config *config.Config
  11. }
  12. func NewNamespaceScopedFactory(
  13. config *config.Config,
  14. ) *NamespaceScopedFactory {
  15. return &NamespaceScopedFactory{config}
  16. }
  17. func (p *NamespaceScopedFactory) Middleware(next http.Handler) http.Handler {
  18. return &NamespaceScopedMiddleware{next, p.config}
  19. }
  20. type NamespaceScopedMiddleware struct {
  21. next http.Handler
  22. config *config.Config
  23. }
  24. func (n *NamespaceScopedMiddleware) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  25. // get the namespace from the URL param context
  26. reqScopes, _ := r.Context().Value(types.RequestScopeCtxKey).(map[types.PermissionScope]*types.RequestAction)
  27. namespace := reqScopes[types.NamespaceScope].Resource.Name
  28. if strings.ToLower(namespace) == "all" {
  29. namespace = ""
  30. }
  31. ctx := NewNamespaceContext(r.Context(), namespace)
  32. r = r.Clone(ctx)
  33. n.next.ServeHTTP(w, r)
  34. }
  35. func NewNamespaceContext(ctx context.Context, namespace string) context.Context {
  36. return context.WithValue(ctx, types.NamespaceScope, namespace)
  37. }