project.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. package authz
  2. import (
  3. "context"
  4. "net/http"
  5. "github.com/porter-dev/porter/api/server/shared"
  6. "github.com/porter-dev/porter/api/server/shared/apierrors"
  7. "github.com/porter-dev/porter/api/types"
  8. "github.com/porter-dev/porter/internal/repository"
  9. )
  10. type ProjectScopedFactory struct {
  11. projectRepo repository.ProjectRepository
  12. config *shared.Config
  13. }
  14. func NewProjectScopedFactory(
  15. projectRepo repository.ProjectRepository,
  16. config *shared.Config,
  17. ) *ProjectScopedFactory {
  18. return &ProjectScopedFactory{projectRepo, config}
  19. }
  20. func (f *ProjectScopedFactory) NewProjectScoped(next http.Handler) http.Handler {
  21. return &ProjectScoped{next, f.projectRepo, f.config}
  22. }
  23. type ProjectScoped struct {
  24. next http.Handler
  25. projectRepo repository.ProjectRepository
  26. config *shared.Config
  27. }
  28. func (scope *ProjectScoped) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  29. // read the project id from the request
  30. _, reqErr := GetURLParamUint(r, "project_id")
  31. if reqErr != nil {
  32. apierrors.HandleAPIError(w, scope.config.Logger, reqErr)
  33. return
  34. }
  35. // find a set of roles for this user and compute a policy document
  36. // determine if policy document allows for project scope
  37. project := types.Project{}
  38. // create a new project-scoped context and serve
  39. r = r.WithContext(NewProjectContext(r.Context(), project))
  40. scope.next.ServeHTTP(w, r)
  41. }
  42. func NewProjectContext(ctx context.Context, project types.Project) context.Context {
  43. return context.WithValue(ctx, types.ProjectScope, project)
  44. }