project.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. package authz
  2. import (
  3. "context"
  4. "net/http"
  5. "github.com/porter-dev/porter/api/server/shared/apierrors"
  6. "github.com/porter-dev/porter/api/server/shared/config"
  7. "github.com/porter-dev/porter/api/types"
  8. "github.com/porter-dev/porter/internal/models"
  9. )
  10. type ProjectScopedFactory struct {
  11. config *config.Config
  12. }
  13. func NewProjectScopedFactory(
  14. config *config.Config,
  15. ) *ProjectScopedFactory {
  16. return &ProjectScopedFactory{config}
  17. }
  18. func (p *ProjectScopedFactory) Middleware(next http.Handler) http.Handler {
  19. return &ProjectScopedMiddleware{next, p.config}
  20. }
  21. type ProjectScopedMiddleware struct {
  22. next http.Handler
  23. config *config.Config
  24. }
  25. func (p *ProjectScopedMiddleware) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  26. // get the project id from the URL param context
  27. reqScopes, _ := r.Context().Value(types.RequestScopeCtxKey).(map[types.PermissionScope]*types.RequestAction)
  28. projID := reqScopes[types.ProjectScope].Resource.UInt
  29. project, err := p.config.Repo.Project().ReadProject(projID)
  30. if err != nil {
  31. apierrors.HandleAPIError(p.config, w, r, apierrors.NewErrInternal(err))
  32. return
  33. }
  34. ctx := NewProjectContext(r.Context(), project)
  35. r = r.Clone(ctx)
  36. p.next.ServeHTTP(w, r)
  37. }
  38. func NewProjectContext(ctx context.Context, project *models.Project) context.Context {
  39. return context.WithValue(ctx, types.ProjectScope, project)
  40. }