git_installation.go 1.9 KB

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