2
0

gitlab_integration.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. ints "github.com/porter-dev/porter/internal/models/integrations"
  11. "gorm.io/gorm"
  12. )
  13. type GitlabIntegrationScopedFactory struct {
  14. config *config.Config
  15. }
  16. func NewGitlabIntegrationScopedFactory(
  17. config *config.Config,
  18. ) *GitlabIntegrationScopedFactory {
  19. return &GitlabIntegrationScopedFactory{config}
  20. }
  21. func (p *GitlabIntegrationScopedFactory) Middleware(next http.Handler) http.Handler {
  22. return &GitlabIntegrationScopedMiddleware{next, p.config}
  23. }
  24. type GitlabIntegrationScopedMiddleware struct {
  25. next http.Handler
  26. config *config.Config
  27. }
  28. func (p *GitlabIntegrationScopedMiddleware) 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 integration id from the URL param context
  32. reqScopes, _ := r.Context().Value(types.RequestScopeCtxKey).(map[types.PermissionScope]*types.RequestAction)
  33. integrationID := reqScopes[types.GitlabIntegrationScope].Resource.UInt
  34. gi, err := p.config.Repo.GitlabIntegration().ReadGitlabIntegration(proj.ID, integrationID)
  35. if err != nil {
  36. if err == gorm.ErrRecordNotFound {
  37. apierrors.HandleAPIError(p.config.Logger, p.config.Alerter, w, r, apierrors.NewErrForbidden(
  38. fmt.Errorf("gitlab integration not found with id %d", integrationID),
  39. ), true)
  40. return
  41. }
  42. apierrors.HandleAPIError(p.config.Logger, p.config.Alerter, w, r, apierrors.NewErrInternal(err), true)
  43. return
  44. }
  45. ctx := NewGitlabIntegrationContext(r.Context(), gi)
  46. r = r.Clone(ctx)
  47. p.next.ServeHTTP(w, r)
  48. }
  49. func NewGitlabIntegrationContext(ctx context.Context, gi *ints.GitlabIntegration) context.Context {
  50. return context.WithValue(ctx, types.GitlabIntegrationScope, gi)
  51. }