infra.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package authz
  2. import (
  3. "context"
  4. "fmt"
  5. "net/http"
  6. "github.com/porter-dev/porter/api/server/shared/apierrors"
  7. "github.com/porter-dev/porter/api/server/shared/config"
  8. "github.com/porter-dev/porter/api/types"
  9. "github.com/porter-dev/porter/internal/models"
  10. "gorm.io/gorm"
  11. )
  12. type InfraScopedFactory struct {
  13. config *config.Config
  14. }
  15. func NewInfraScopedFactory(
  16. config *config.Config,
  17. ) *InfraScopedFactory {
  18. return &InfraScopedFactory{config}
  19. }
  20. func (p *InfraScopedFactory) Middleware(next http.Handler) http.Handler {
  21. return &InfraScopedMiddleware{next, p.config}
  22. }
  23. type InfraScopedMiddleware struct {
  24. next http.Handler
  25. config *config.Config
  26. }
  27. func (p *InfraScopedMiddleware) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  28. // read the project to check scopes
  29. proj, _ := r.Context().Value(types.ProjectScope).(*models.Project)
  30. // get the registry id from the URL param context
  31. reqScopes, _ := r.Context().Value(types.RequestScopeCtxKey).(map[types.PermissionScope]*types.RequestAction)
  32. infraID := reqScopes[types.InfraScope].Resource.UInt
  33. infra, err := p.config.Repo.Infra().ReadInfra(proj.ID, infraID)
  34. if err != nil {
  35. if err == gorm.ErrRecordNotFound {
  36. apierrors.HandleAPIError(p.config.Logger, p.config.Alerter, w, r, apierrors.NewErrForbidden(
  37. fmt.Errorf("infra with id %d not found in project %d", infraID, proj.ID),
  38. ), true)
  39. } else {
  40. apierrors.HandleAPIError(p.config.Logger, p.config.Alerter, w, r, apierrors.NewErrInternal(err), true)
  41. }
  42. return
  43. }
  44. ctx := NewInfraContext(r.Context(), infra)
  45. r = r.Clone(ctx)
  46. p.next.ServeHTTP(w, r)
  47. }
  48. func NewInfraContext(ctx context.Context, infra *models.Infra) context.Context {
  49. return context.WithValue(ctx, types.InfraScope, infra)
  50. }