github_callback.go 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  1. package user
  2. import (
  3. "context"
  4. "fmt"
  5. "net/http"
  6. "net/url"
  7. "strings"
  8. "golang.org/x/oauth2"
  9. "gorm.io/gorm"
  10. "github.com/google/go-github/github"
  11. "github.com/porter-dev/porter/api/server/authn"
  12. "github.com/porter-dev/porter/api/server/handlers"
  13. "github.com/porter-dev/porter/api/server/shared"
  14. "github.com/porter-dev/porter/api/server/shared/apierrors"
  15. "github.com/porter-dev/porter/api/server/shared/config"
  16. "github.com/porter-dev/porter/internal/analytics"
  17. "github.com/porter-dev/porter/internal/models"
  18. )
  19. type UserOAuthGithubCallbackHandler struct {
  20. handlers.PorterHandlerReadWriter
  21. }
  22. func NewUserOAuthGithubCallbackHandler(
  23. config *config.Config,
  24. decoderValidator shared.RequestDecoderValidator,
  25. writer shared.ResultWriter,
  26. ) *UserOAuthGithubCallbackHandler {
  27. return &UserOAuthGithubCallbackHandler{
  28. PorterHandlerReadWriter: handlers.NewDefaultPorterHandler(config, decoderValidator, writer),
  29. }
  30. }
  31. func (p *UserOAuthGithubCallbackHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  32. session, err := p.Config().Store.Get(r, p.Config().ServerConf.CookieName)
  33. if err != nil {
  34. p.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  35. return
  36. }
  37. if _, ok := session.Values["state"]; !ok {
  38. p.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  39. return
  40. }
  41. if r.URL.Query().Get("state") != session.Values["state"] {
  42. p.HandleAPIError(w, r, apierrors.NewErrForbidden(err))
  43. return
  44. }
  45. token, err := p.Config().GithubConf.Exchange(oauth2.NoContext, r.URL.Query().Get("code"))
  46. if err != nil {
  47. p.HandleAPIError(w, r, apierrors.NewErrForbidden(err))
  48. return
  49. }
  50. if !token.Valid() {
  51. p.HandleAPIError(w, r, apierrors.NewErrForbidden(fmt.Errorf("invalid token")))
  52. return
  53. }
  54. // otherwise, create the user if not exists
  55. user, err := upsertUserFromToken(p.Config(), token)
  56. if err != nil && strings.Contains(err.Error(), "already registered") {
  57. http.Redirect(w, r, "/login?error="+url.QueryEscape(err.Error()), 302)
  58. return
  59. } else if err != nil {
  60. http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
  61. return
  62. }
  63. p.Config().AnalyticsClient.Identify(analytics.CreateSegmentIdentifyUser(user))
  64. // save the user as authenticated in the session
  65. if err := authn.SaveUserAuthenticated(w, r, p.Config(), user); err != nil {
  66. p.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  67. return
  68. }
  69. // non-fatal send email verification
  70. if !user.EmailVerified {
  71. startEmailVerification(p.Config(), w, r, user)
  72. }
  73. if redirectStr, ok := session.Values["redirect_uri"].(string); ok && redirectStr != "" {
  74. // attempt to parse the redirect uri, if it fails just redirect to dashboard
  75. redirectURI, err := url.Parse(redirectStr)
  76. if err != nil {
  77. http.Redirect(w, r, "/dashboard", 302)
  78. }
  79. http.Redirect(w, r, fmt.Sprintf("%s?%s", redirectURI.Path, redirectURI.RawQuery), 302)
  80. } else {
  81. http.Redirect(w, r, "/dashboard", 302)
  82. }
  83. }
  84. func upsertUserFromToken(config *config.Config, tok *oauth2.Token) (*models.User, error) {
  85. // determine if the user already exists
  86. client := github.NewClient(config.GithubConf.Client(oauth2.NoContext, tok))
  87. githubUser, _, err := client.Users.Get(context.Background(), "")
  88. if err != nil {
  89. return nil, err
  90. }
  91. user, err := config.Repo.User().ReadUserByGithubUserID(*githubUser.ID)
  92. // if the user does not exist, create new user
  93. if err != nil && err == gorm.ErrRecordNotFound {
  94. emails, _, err := client.Users.ListEmails(context.Background(), &github.ListOptions{})
  95. if err != nil {
  96. return nil, err
  97. }
  98. primary := ""
  99. verified := false
  100. // get the primary email
  101. for _, email := range emails {
  102. if email.GetPrimary() {
  103. primary = email.GetEmail()
  104. verified = email.GetVerified()
  105. break
  106. }
  107. }
  108. if primary == "" {
  109. return nil, fmt.Errorf("github user must have an email")
  110. }
  111. if err := checkUserRestrictions(config.ServerConf, primary); err != nil {
  112. return nil, err
  113. }
  114. // check if a user with that email address already exists
  115. _, err = config.Repo.User().ReadUserByEmail(primary)
  116. if err == gorm.ErrRecordNotFound {
  117. user = &models.User{
  118. Email: primary,
  119. EmailVerified: !config.Metadata.Email || verified,
  120. GithubUserID: githubUser.GetID(),
  121. }
  122. user, err = config.Repo.User().CreateUser(user)
  123. if err != nil {
  124. return nil, err
  125. }
  126. config.AnalyticsClient.Track(analytics.UserCreateTrack(&analytics.UserCreateTrackOpts{
  127. UserScopedTrackOpts: analytics.GetUserScopedTrackOpts(user.ID),
  128. Email: user.Email,
  129. }))
  130. } else if err == nil {
  131. return nil, fmt.Errorf("email already registered")
  132. } else if err != nil {
  133. return nil, err
  134. }
  135. } else if err != nil {
  136. return nil, fmt.Errorf("unexpected error occurred:%s", err.Error())
  137. }
  138. return user, nil
  139. }