list_gitlab.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. package project_integration
  2. import (
  3. "net/http"
  4. ints "github.com/porter-dev/porter/internal/models/integrations"
  5. "github.com/porter-dev/porter/api/server/handlers"
  6. "github.com/porter-dev/porter/api/server/shared"
  7. "github.com/porter-dev/porter/api/server/shared/apierrors"
  8. "github.com/porter-dev/porter/api/server/shared/config"
  9. "github.com/porter-dev/porter/api/types"
  10. "github.com/porter-dev/porter/internal/models"
  11. )
  12. type ListGitlabHandler struct {
  13. handlers.PorterHandlerWriter
  14. }
  15. func NewListGitlabHandler(
  16. config *config.Config,
  17. writer shared.ResultWriter,
  18. ) *ListGitlabHandler {
  19. return &ListGitlabHandler{
  20. PorterHandlerWriter: handlers.NewDefaultPorterHandler(config, nil, writer),
  21. }
  22. }
  23. func (p *ListGitlabHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  24. project, _ := r.Context().Value(types.ProjectScope).(*models.Project)
  25. user, _ := r.Context().Value(types.UserScope).(*models.User)
  26. gitlabInts, err := p.Repo().GitlabIntegration().ListGitlabIntegrationsByProjectID(project.ID)
  27. if err != nil {
  28. p.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  29. return
  30. }
  31. var res types.ListGitlabResponse = make([]*types.GitlabIntegrationWithUsername, 0)
  32. for _, gitlabInt := range gitlabInts {
  33. username := p.getCurrentUsername(user.ID, project.ID, gitlabInt)
  34. glit := gitlabInt.ToGitlabIntegrationType()
  35. res = append(res,
  36. &types.GitlabIntegrationWithUsername{
  37. Username: username,
  38. GitlabIntegration: *glit,
  39. },
  40. )
  41. }
  42. p.WriteResult(w, r, res)
  43. }
  44. func (p *ListGitlabHandler) getCurrentUsername(userID uint, projectID uint, gi *ints.GitlabIntegration) string {
  45. client, err := getGitlabClient(p.Repo(), userID, projectID, gi, p.Config())
  46. if err != nil {
  47. return "Unable to connect"
  48. }
  49. currentUser, resp, err := client.Users.CurrentUser()
  50. if resp.StatusCode == http.StatusUnauthorized {
  51. return "Unable to connect"
  52. }
  53. if err != nil {
  54. return "Unable to connect"
  55. }
  56. return currentUser.Username
  57. }