2
0

create_gitlab.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. package project_integration
  2. import (
  3. "fmt"
  4. "net/http"
  5. "net/url"
  6. "github.com/porter-dev/porter/api/server/handlers"
  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/server/shared/config"
  10. "github.com/porter-dev/porter/api/types"
  11. "github.com/porter-dev/porter/internal/models"
  12. ints "github.com/porter-dev/porter/internal/models/integrations"
  13. )
  14. type CreateGitlabIntegration struct {
  15. handlers.PorterHandlerReadWriter
  16. }
  17. func NewCreateGitlabIntegration(
  18. config *config.Config,
  19. decoderValidator shared.RequestDecoderValidator,
  20. writer shared.ResultWriter,
  21. ) *CreateGitlabIntegration {
  22. return &CreateGitlabIntegration{
  23. PorterHandlerReadWriter: handlers.NewDefaultPorterHandler(config, decoderValidator, writer),
  24. }
  25. }
  26. func (p *CreateGitlabIntegration) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  27. project, _ := r.Context().Value(types.ProjectScope).(*models.Project)
  28. metadata := p.Config().Metadata
  29. if !metadata.Gitlab {
  30. p.HandleAPIError(w, r, apierrors.NewErrForbidden(fmt.Errorf("gitlab integration endpoints are not enabled")))
  31. return
  32. }
  33. request := &types.CreateGitlabRequest{}
  34. if ok := p.DecodeAndValidate(w, r, request); !ok {
  35. return
  36. }
  37. _, err := url.Parse(request.InstanceURL)
  38. if err != nil {
  39. p.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(
  40. fmt.Errorf("malformed gitlab instance URL"), http.StatusBadRequest,
  41. ))
  42. return
  43. }
  44. gitlabIntegration, err := p.Repo().GitlabIntegration().CreateGitlabIntegration(&ints.GitlabIntegration{
  45. ProjectID: project.ID,
  46. InstanceURL: request.InstanceURL,
  47. AppClientID: []byte(request.AppClientID),
  48. AppClientSecret: []byte(request.AppClientSecret),
  49. })
  50. if err != nil {
  51. p.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  52. return
  53. }
  54. res := types.CreateGitlabResponse{
  55. GitlabIntegration: gitlabIntegration.ToGitlabIntegrationType(),
  56. }
  57. p.WriteResult(w, r, res)
  58. }