list_gitlab.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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. res = append(res,
  35. &types.GitlabIntegrationWithUsername{
  36. *gitlabInt.ToGitlabIntegrationType(),
  37. username,
  38. },
  39. )
  40. }
  41. p.WriteResult(w, r, res)
  42. }
  43. func (p *ListGitlabHandler) getCurrentUsername(userID uint, projectID uint, gi *ints.GitlabIntegration) string {
  44. client, err := getGitlabClient(p.Repo(), userID, projectID, gi, p.Config())
  45. if err != nil {
  46. return "Unable to connect"
  47. }
  48. currentUser, resp, err := client.Users.CurrentUser()
  49. if resp.StatusCode == http.StatusUnauthorized {
  50. return "Unable to connect"
  51. }
  52. if err != nil {
  53. return "Unable to connect"
  54. }
  55. return currentUser.Username
  56. }