gitlab.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. package project_oauth
  2. import (
  3. "fmt"
  4. "net/http"
  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/commonutils"
  9. "github.com/porter-dev/porter/api/server/shared/config"
  10. "github.com/porter-dev/porter/api/server/shared/requestutils"
  11. "github.com/porter-dev/porter/api/types"
  12. "github.com/porter-dev/porter/internal/models"
  13. "github.com/porter-dev/porter/internal/oauth"
  14. "golang.org/x/oauth2"
  15. "gorm.io/gorm"
  16. )
  17. type ProjectOAuthGitlabHandler struct {
  18. handlers.PorterHandlerReadWriter
  19. }
  20. func NewProjectOAuthGitlabHandler(
  21. config *config.Config,
  22. decoderValidator shared.RequestDecoderValidator,
  23. writer shared.ResultWriter,
  24. ) *ProjectOAuthGitlabHandler {
  25. return &ProjectOAuthGitlabHandler{
  26. PorterHandlerReadWriter: handlers.NewDefaultPorterHandler(config, decoderValidator, writer),
  27. }
  28. }
  29. func (p *ProjectOAuthGitlabHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  30. proj, _ := r.Context().Value(types.ProjectScope).(*models.Project)
  31. integrationID, reqErr := requestutils.GetURLParamUint(r, "integration_id")
  32. if reqErr != nil {
  33. p.HandleAPIError(w, r, reqErr)
  34. return
  35. }
  36. giIntegration, err := p.Repo().GitlabIntegration().ReadGitlabIntegration(proj.ID, integrationID)
  37. if err != nil {
  38. if err == gorm.ErrRecordNotFound {
  39. p.HandleAPIError(w, r, apierrors.NewErrForbidden(
  40. fmt.Errorf("gitlab integration with id %d not found in project %d", integrationID, proj.ID),
  41. ))
  42. } else {
  43. p.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  44. }
  45. return
  46. }
  47. state := oauth.CreateRandomState()
  48. if err := p.PopulateOAuthSession(w, r, state, true, true, types.OAuthGitlab, integrationID); err != nil {
  49. p.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  50. return
  51. }
  52. gitlabConf := commonutils.GetGitlabOAuthConf(p.Config(), giIntegration)
  53. // specify access type offline to get a refresh token
  54. url := gitlabConf.AuthCodeURL(state, oauth2.AccessTypeOffline)
  55. http.Redirect(w, r, url, http.StatusFound)
  56. }