registry.go 1.8 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 RegistryScopedFactory struct {
  13. config *config.Config
  14. }
  15. func NewRegistryScopedFactory(
  16. config *config.Config,
  17. ) *RegistryScopedFactory {
  18. return &RegistryScopedFactory{config}
  19. }
  20. func (p *RegistryScopedFactory) Middleware(next http.Handler) http.Handler {
  21. return &RegistryScopedMiddleware{next, p.config}
  22. }
  23. type RegistryScopedMiddleware struct {
  24. next http.Handler
  25. config *config.Config
  26. }
  27. func (p *RegistryScopedMiddleware) 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. registryID := reqScopes[types.RegistryScope].Resource.UInt
  33. registry, err := p.config.Repo.Registry().ReadRegistry(proj.ID, registryID)
  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("registry with id %d not found in project %d", registryID, 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 := NewRegistryContext(r.Context(), registry)
  45. r = r.Clone(ctx)
  46. p.next.ServeHTTP(w, r)
  47. }
  48. func NewRegistryContext(ctx context.Context, registry *models.Registry) context.Context {
  49. return context.WithValue(ctx, types.RegistryScope, registry)
  50. }