2
0

oauth_callback.go 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  1. package gitinstallation
  2. import (
  3. "fmt"
  4. "net/http"
  5. "net/url"
  6. "github.com/porter-dev/porter/internal/telemetry"
  7. "github.com/porter-dev/porter/api/server/handlers"
  8. "github.com/porter-dev/porter/api/server/shared"
  9. "github.com/porter-dev/porter/api/server/shared/apierrors"
  10. "github.com/porter-dev/porter/api/server/shared/config"
  11. "github.com/porter-dev/porter/api/types"
  12. "github.com/porter-dev/porter/internal/analytics"
  13. "github.com/porter-dev/porter/internal/models"
  14. "github.com/porter-dev/porter/internal/models/integrations"
  15. "golang.org/x/oauth2"
  16. )
  17. type GithubAppOAuthCallbackHandler struct {
  18. handlers.PorterHandlerReadWriter
  19. }
  20. func NewGithubAppOAuthCallbackHandler(
  21. config *config.Config,
  22. decoderValidator shared.RequestDecoderValidator,
  23. writer shared.ResultWriter,
  24. ) *GithubAppOAuthCallbackHandler {
  25. return &GithubAppOAuthCallbackHandler{
  26. PorterHandlerReadWriter: handlers.NewDefaultPorterHandler(config, decoderValidator, writer),
  27. }
  28. }
  29. func (c *GithubAppOAuthCallbackHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  30. ctx, span := telemetry.NewSpan(r.Context(), "serve-github-app-oauth-callback")
  31. defer span.End()
  32. r = r.Clone(ctx)
  33. user, _ := r.Context().Value(types.UserScope).(*models.User)
  34. telemetry.WithAttributes(span, telemetry.AttributeKV{Key: "user-id", Value: user.ID})
  35. session, err := c.Config().Store.Get(r, c.Config().ServerConf.CookieName)
  36. if err != nil {
  37. err = telemetry.Error(ctx, span, err, "error getting session")
  38. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusInternalServerError))
  39. return
  40. }
  41. token, err := c.Config().GithubAppConf.Exchange(oauth2.NoContext, r.URL.Query().Get("code"))
  42. if err != nil || !token.Valid() {
  43. telemetry.WithAttributes(span,
  44. telemetry.AttributeKV{Key: "token-valid", Value: token.Valid()},
  45. telemetry.AttributeKV{Key: "token-error", Value: err.Error()},
  46. )
  47. if redirectStr, ok := session.Values["redirect_uri"].(string); ok && redirectStr != "" {
  48. telemetry.WithAttributes(span, telemetry.AttributeKV{Key: "redirect-uri", Value: redirectStr})
  49. // attempt to parse the redirect uri, if it fails just redirect to dashboard
  50. redirectURI, err := url.Parse(redirectStr)
  51. if err != nil {
  52. telemetry.WithAttributes(span, telemetry.AttributeKV{Key: "redirect-uri-parse-error", Value: err.Error()})
  53. http.Redirect(w, r, "/dashboard", 302)
  54. }
  55. http.Redirect(w, r, fmt.Sprintf("%s?%s", redirectURI.Path, redirectURI.RawQuery), 302)
  56. } else {
  57. http.Redirect(w, r, "/dashboard", 302)
  58. }
  59. return
  60. }
  61. oauthInt := &integrations.GithubAppOAuthIntegration{
  62. SharedOAuthModel: integrations.SharedOAuthModel{
  63. AccessToken: []byte(token.AccessToken),
  64. RefreshToken: []byte(token.RefreshToken),
  65. Expiry: token.Expiry,
  66. },
  67. UserID: user.ID,
  68. }
  69. oauthInt, err = c.Repo().GithubAppOAuthIntegration().CreateGithubAppOAuthIntegration(oauthInt)
  70. if err != nil {
  71. err = telemetry.Error(ctx, span, err, "error creating github app oauth integration")
  72. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusInternalServerError))
  73. return
  74. }
  75. user.GithubAppIntegrationID = oauthInt.ID
  76. user, err = c.Repo().User().UpdateUser(user)
  77. if err != nil {
  78. err = telemetry.Error(ctx, span, err, "error updating user")
  79. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusInternalServerError))
  80. return
  81. }
  82. c.Config().AnalyticsClient.Track(analytics.GithubConnectionSuccessTrack(
  83. &analytics.GithubConnectionSuccessTrackOpts{
  84. UserScopedTrackOpts: analytics.GetUserScopedTrackOpts(user.ID),
  85. },
  86. ))
  87. if redirectStr, ok := session.Values["redirect_uri"].(string); ok && redirectStr != "" {
  88. telemetry.WithAttributes(span, telemetry.AttributeKV{Key: "redirect-uri", Value: redirectStr})
  89. // attempt to parse the redirect uri, if it fails just redirect to dashboard
  90. redirectURI, err := url.Parse(redirectStr)
  91. if err != nil {
  92. telemetry.WithAttributes(span, telemetry.AttributeKV{Key: "redirect-uri-parse-error", Value: err.Error()})
  93. http.Redirect(w, r, "/dashboard", 302)
  94. }
  95. http.Redirect(w, r, fmt.Sprintf("%s?%s", redirectURI.Path, redirectURI.RawQuery), 302)
  96. } else {
  97. http.Redirect(w, r, "/dashboard", 302)
  98. }
  99. }