2
0

infra.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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/requestutils"
  8. "github.com/porter-dev/porter/api/types"
  9. "github.com/porter-dev/porter/internal/models"
  10. "github.com/porter-dev/porter/provisioner/server/config"
  11. "gorm.io/gorm"
  12. )
  13. type InfraScopedFactory struct {
  14. config *config.Config
  15. }
  16. func NewInfraScopedFactory(
  17. config *config.Config,
  18. ) *InfraScopedFactory {
  19. return &InfraScopedFactory{config}
  20. }
  21. func (p *InfraScopedFactory) Middleware(next http.Handler) http.Handler {
  22. return &InfraScopedMiddleware{next, p.config}
  23. }
  24. type InfraScopedMiddleware struct {
  25. next http.Handler
  26. config *config.Config
  27. }
  28. func (p *InfraScopedMiddleware) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  29. proj, _ := r.Context().Value(types.ProjectScope).(*models.Project)
  30. infraID, reqErr := requestutils.GetURLParamUint(r, types.URLParam("infra_id"))
  31. if reqErr != nil {
  32. apierrors.HandleAPIError(
  33. p.config.Logger,
  34. p.config.Alerter, w, r,
  35. apierrors.NewErrForbidden(
  36. fmt.Errorf("could not get infra id: %s", reqErr.Error()),
  37. ),
  38. true,
  39. )
  40. return
  41. }
  42. // look for infra with that ID and project ID
  43. infra, err := p.config.Repo.Infra().ReadInfra(proj.ID, infraID)
  44. if err != nil {
  45. if err == gorm.ErrRecordNotFound {
  46. apierrors.HandleAPIError(
  47. p.config.Logger,
  48. p.config.Alerter, w, r,
  49. apierrors.NewErrForbidden(
  50. fmt.Errorf("could not read infra id %d in project %d", infraID, proj.ID),
  51. ),
  52. true,
  53. )
  54. } else {
  55. apierrors.HandleAPIError(p.config.Logger, p.config.Alerter, w, r, apierrors.NewErrInternal(err), true)
  56. }
  57. return
  58. }
  59. ctx := NewInfraContext(r.Context(), infra)
  60. r = r.Clone(ctx)
  61. p.next.ServeHTTP(w, r)
  62. }
  63. func NewInfraContext(ctx context.Context, infra *models.Infra) context.Context {
  64. return context.WithValue(ctx, types.InfraScope, infra)
  65. }