helm_repo.go 1.8 KB

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