oauth_google_handler.go 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  1. package api
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "io/ioutil"
  6. "net/http"
  7. "net/url"
  8. "strings"
  9. "github.com/porter-dev/porter/internal/analytics"
  10. "github.com/porter-dev/porter/internal/models"
  11. "gorm.io/gorm"
  12. "github.com/porter-dev/porter/internal/oauth"
  13. "golang.org/x/oauth2"
  14. )
  15. // HandleGoogleStartUser starts the oauth2 flow for a user login request.
  16. func (app *App) HandleGoogleStartUser(w http.ResponseWriter, r *http.Request) {
  17. state := oauth.CreateRandomState()
  18. err := app.populateOAuthSession(w, r, state, false)
  19. if err != nil {
  20. app.handleErrorDataRead(err, w)
  21. return
  22. }
  23. // specify access type offline to get a refresh token
  24. url := app.GoogleUserConf.AuthCodeURL(state, oauth2.AccessTypeOnline)
  25. http.Redirect(w, r, url, 302)
  26. }
  27. // HandleGithubOAuthCallback verifies the callback request by checking that the
  28. // state parameter has not been modified, and validates the token.
  29. //
  30. // When logging a user in, the access token gets stored in the session, and no refresh
  31. // token is requested. We store the access token in the session because a user can be
  32. // logged in multiple times with a single access token.
  33. func (app *App) HandleGoogleOAuthCallback(w http.ResponseWriter, r *http.Request) {
  34. session, err := app.Store.Get(r, app.ServerConf.CookieName)
  35. if err != nil {
  36. app.handleErrorDataRead(err, w)
  37. return
  38. }
  39. if _, ok := session.Values["state"]; !ok {
  40. app.sendExternalError(
  41. err,
  42. http.StatusForbidden,
  43. HTTPError{
  44. Code: http.StatusForbidden,
  45. Errors: []string{
  46. "Could not read cookie: are cookies enabled?",
  47. },
  48. },
  49. w,
  50. )
  51. return
  52. }
  53. if r.URL.Query().Get("state") != session.Values["state"] {
  54. http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
  55. return
  56. }
  57. token, err := app.GoogleUserConf.Exchange(oauth2.NoContext, r.URL.Query().Get("code"))
  58. if err != nil {
  59. http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
  60. return
  61. }
  62. if !token.Valid() {
  63. http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
  64. return
  65. }
  66. // create the user if not exists
  67. user, err := app.upsertGoogleUserFromToken(token)
  68. if err != nil && strings.Contains(err.Error(), "already registered") {
  69. http.Redirect(w, r, "/login?error="+url.QueryEscape(err.Error()), 302)
  70. return
  71. } else if err != nil && strings.Contains(err.Error(), "restricted domain group") {
  72. http.Redirect(w, r, "/login?error="+url.QueryEscape(err.Error()), 302)
  73. return
  74. } else if err != nil {
  75. http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
  76. return
  77. }
  78. // send to segment
  79. app.analyticsClient.Identify(analytics.CreateSegmentIdentifyNewUser(user, true))
  80. app.analyticsClient.Track(analytics.CreateSegmentNewUserTrack(user))
  81. // log the user in
  82. app.Logger.Info().Msgf("New user created: %d", user.ID)
  83. session.Values["authenticated"] = true
  84. session.Values["user_id"] = user.ID
  85. session.Values["email"] = user.Email
  86. session.Values["redirect"] = ""
  87. session.Save(r, w)
  88. if session.Values["query_params"] != "" {
  89. http.Redirect(w, r, fmt.Sprintf("/dashboard?%s", session.Values["query_params"]), 302)
  90. } else {
  91. http.Redirect(w, r, "/dashboard", 302)
  92. }
  93. }
  94. type googleUserInfo struct {
  95. Email string `json:"email"`
  96. EmailVerified bool `json:"email_verified"`
  97. HD string `json:"hd"`
  98. Sub string `json:"sub"`
  99. }
  100. func (app *App) upsertGoogleUserFromToken(tok *oauth2.Token) (*models.User, error) {
  101. gInfo, err := getGoogleUserInfoFromToken(tok)
  102. if err != nil {
  103. return nil, err
  104. }
  105. // if the app has a restricted domain, check the `hd` query param
  106. if app.ServerConf.GoogleRestrictedDomain != "" {
  107. if gInfo.HD != app.ServerConf.GoogleRestrictedDomain {
  108. return nil, fmt.Errorf("Email is not in the restricted domain group.")
  109. }
  110. }
  111. user, err := app.Repo.User.ReadUserByGoogleUserID(gInfo.Sub)
  112. // if the user does not exist, create new user
  113. if err != nil && err == gorm.ErrRecordNotFound {
  114. // check if a user with that email address already exists
  115. _, err = app.Repo.User.ReadUserByEmail(gInfo.Email)
  116. if err == gorm.ErrRecordNotFound {
  117. user = &models.User{
  118. Email: gInfo.Email,
  119. EmailVerified: gInfo.EmailVerified,
  120. GoogleUserID: gInfo.Sub,
  121. }
  122. user, err = app.Repo.User.CreateUser(user)
  123. if err != nil {
  124. return nil, err
  125. }
  126. } else if err == nil {
  127. return nil, fmt.Errorf("email already registered")
  128. } else if err != nil {
  129. return nil, err
  130. }
  131. } else if err != nil {
  132. return nil, fmt.Errorf("unexpected error occurred:%s", err.Error())
  133. }
  134. return user, nil
  135. }
  136. func getGoogleUserInfoFromToken(tok *oauth2.Token) (*googleUserInfo, error) {
  137. // use userinfo endpoint for Google OIDC to get claims
  138. url := "https://openidconnect.googleapis.com/v1/userinfo"
  139. req, err := http.NewRequest("GET", url, nil)
  140. req.Header.Add("Authorization", "Bearer "+tok.AccessToken)
  141. client := &http.Client{}
  142. response, err := client.Do(req)
  143. if err != nil {
  144. return nil, fmt.Errorf("failed getting user info: %s", err.Error())
  145. }
  146. defer response.Body.Close()
  147. contents, err := ioutil.ReadAll(response.Body)
  148. if err != nil {
  149. return nil, fmt.Errorf("failed reading response body: %s", err.Error())
  150. }
  151. // parse contents into Google userinfo claims
  152. gInfo := &googleUserInfo{}
  153. err = json.Unmarshal(contents, &gInfo)
  154. return gInfo, nil
  155. }