neon.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. package project_oauth
  2. import (
  3. "net/http"
  4. "github.com/porter-dev/porter/internal/telemetry"
  5. "golang.org/x/oauth2"
  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/internal/oauth"
  11. )
  12. // ProjectOAuthNeonHandler is the handler which redirects to the neon oauth flow
  13. type ProjectOAuthNeonHandler struct {
  14. handlers.PorterHandlerReadWriter
  15. }
  16. // NewProjectOAuthNeonHandler generates a new ProjectOAuthNeonHandler
  17. func NewProjectOAuthNeonHandler(
  18. config *config.Config,
  19. decoderValidator shared.RequestDecoderValidator,
  20. writer shared.ResultWriter,
  21. ) *ProjectOAuthNeonHandler {
  22. return &ProjectOAuthNeonHandler{
  23. PorterHandlerReadWriter: handlers.NewDefaultPorterHandler(config, decoderValidator, writer),
  24. }
  25. }
  26. // ServeHTTP populates the oauth session with state and project id then redirects the user to the neon oauth flow
  27. func (p *ProjectOAuthNeonHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  28. ctx, span := telemetry.NewSpan(r.Context(), "serve-project-oauth-neon")
  29. defer span.End()
  30. r = r.Clone(ctx)
  31. state := oauth.CreateRandomState()
  32. if err := p.PopulateOAuthSession(ctx, w, r, state, true, false, "", 0); err != nil {
  33. err = telemetry.Error(ctx, span, err, "population oauth session failed")
  34. p.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusInternalServerError))
  35. return
  36. }
  37. url := p.Config().NeonConf.AuthCodeURL(state, oauth2.AccessTypeOffline)
  38. http.Redirect(w, r, url, http.StatusFound)
  39. }