cluster.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. package authz
  2. import (
  3. "context"
  4. "net/http"
  5. "github.com/porter-dev/porter/api/server/authz/policy"
  6. "github.com/porter-dev/porter/api/server/shared"
  7. "github.com/porter-dev/porter/api/server/shared/apierrors"
  8. "github.com/porter-dev/porter/api/types"
  9. "github.com/porter-dev/porter/internal/models"
  10. )
  11. type ClusterScopedFactory struct {
  12. config *shared.Config
  13. }
  14. func NewClusterScopedFactory(
  15. config *shared.Config,
  16. ) *ClusterScopedFactory {
  17. return &ClusterScopedFactory{config}
  18. }
  19. func (p *ClusterScopedFactory) Middleware(next http.Handler) http.Handler {
  20. return &ClusterScopedMiddleware{next, p.config}
  21. }
  22. type ClusterScopedMiddleware struct {
  23. next http.Handler
  24. config *shared.Config
  25. }
  26. func (p *ClusterScopedMiddleware) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  27. // get the project id from the URL param context
  28. reqScopes, _ := r.Context().Value(RequestScopeCtxKey).(map[types.PermissionScope]*policy.RequestAction)
  29. clusterID := reqScopes[types.ClusterScope].Resource.UInt
  30. cluster, err := p.config.Repo.Cluster().ReadCluster(clusterID)
  31. if err != nil {
  32. apierrors.HandleAPIError(w, p.config.Logger, apierrors.NewErrInternal(err))
  33. return
  34. }
  35. ctx := NewClusterContext(r.Context(), cluster)
  36. r = r.WithContext(ctx)
  37. p.next.ServeHTTP(w, r)
  38. }
  39. func NewClusterContext(ctx context.Context, cluster *models.Cluster) context.Context {
  40. return context.WithValue(ctx, types.ClusterScope, cluster)
  41. }