git_installation.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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. "github.com/porter-dev/porter/internal/models/integrations"
  12. "gorm.io/gorm"
  13. )
  14. type GitInstallationScopedFactory struct {
  15. config *shared.Config
  16. }
  17. func NewGitInstallationScopedFactory(
  18. config *shared.Config,
  19. ) *GitInstallationScopedFactory {
  20. return &GitInstallationScopedFactory{config}
  21. }
  22. func (p *GitInstallationScopedFactory) Middleware(next http.Handler) http.Handler {
  23. return &GitInstallationScopedMiddleware{next, p.config}
  24. }
  25. type GitInstallationScopedMiddleware struct {
  26. next http.Handler
  27. config *shared.Config
  28. }
  29. func (p *GitInstallationScopedMiddleware) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  30. // read the project to check scopes
  31. proj, _ := r.Context().Value(types.ProjectScope).(*models.Project)
  32. // get the registry id from the URL param context
  33. reqScopes, _ := r.Context().Value(RequestScopeCtxKey).(map[types.PermissionScope]*policy.RequestAction)
  34. gitInstallationID := reqScopes[types.GitInstallationScope].Resource.UInt
  35. gitInstallation, err := p.config.Repo.GithubAppInstallation().ReadGithubAppInstallation(proj.ID, gitInstallationID)
  36. if err != nil {
  37. if err == gorm.ErrRecordNotFound {
  38. apierrors.HandleAPIError(w, p.config.Logger, apierrors.NewErrForbidden(
  39. fmt.Errorf("github app installation with id %d not found in project %d", gitInstallationID, proj.ID),
  40. ))
  41. } else {
  42. apierrors.HandleAPIError(w, p.config.Logger, apierrors.NewErrInternal(err))
  43. }
  44. return
  45. }
  46. ctx := NewGitInstallationContext(r.Context(), gitInstallation)
  47. r = r.WithContext(ctx)
  48. p.next.ServeHTTP(w, r)
  49. }
  50. func NewGitInstallationContext(ctx context.Context, ga *integrations.GithubAppInstallation) context.Context {
  51. return context.WithValue(ctx, types.GitInstallationScope, ga)
  52. }