oauth_google_handler.go 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  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.CreateSegmentIdentifyUser(user))
  80. app.AnalyticsClient.Track(analytics.UserCreateTrack(&analytics.UserCreateTrackOpts{
  81. UserScopedTrackOpts: analytics.GetUserScopedTrackOpts(user.ID),
  82. Email: user.Email,
  83. }))
  84. // log the user in
  85. app.Logger.Info().Msgf("New user created: %d", user.ID)
  86. session.Values["authenticated"] = true
  87. session.Values["user_id"] = user.ID
  88. session.Values["email"] = user.Email
  89. session.Values["redirect"] = ""
  90. session.Save(r, w)
  91. if session.Values["query_params"] != "" {
  92. http.Redirect(w, r, fmt.Sprintf("/dashboard?%s", session.Values["query_params"]), 302)
  93. } else {
  94. http.Redirect(w, r, "/dashboard", 302)
  95. }
  96. }
  97. type googleUserInfo struct {
  98. Email string `json:"email"`
  99. EmailVerified bool `json:"email_verified"`
  100. HD string `json:"hd"`
  101. Sub string `json:"sub"`
  102. }
  103. func (app *App) upsertGoogleUserFromToken(tok *oauth2.Token) (*models.User, error) {
  104. gInfo, err := getGoogleUserInfoFromToken(tok)
  105. if err != nil {
  106. return nil, err
  107. }
  108. // if the app has a restricted domain, check the `hd` query param
  109. if app.ServerConf.GoogleRestrictedDomain != "" {
  110. if gInfo.HD != app.ServerConf.GoogleRestrictedDomain {
  111. return nil, fmt.Errorf("Email is not in the restricted domain group.")
  112. }
  113. }
  114. user, err := app.Repo.User.ReadUserByGoogleUserID(gInfo.Sub)
  115. // if the user does not exist, create new user
  116. if err != nil && err == gorm.ErrRecordNotFound {
  117. // check if a user with that email address already exists
  118. _, err = app.Repo.User.ReadUserByEmail(gInfo.Email)
  119. if err == gorm.ErrRecordNotFound {
  120. user = &models.User{
  121. Email: gInfo.Email,
  122. EmailVerified: !app.Capabilities.Email || gInfo.EmailVerified,
  123. GoogleUserID: gInfo.Sub,
  124. }
  125. user, err = app.Repo.User.CreateUser(user)
  126. if err != nil {
  127. return nil, err
  128. }
  129. } else if err == nil {
  130. return nil, fmt.Errorf("email already registered")
  131. } else if err != nil {
  132. return nil, err
  133. }
  134. } else if err != nil {
  135. return nil, fmt.Errorf("unexpected error occurred:%s", err.Error())
  136. }
  137. return user, nil
  138. }
  139. func getGoogleUserInfoFromToken(tok *oauth2.Token) (*googleUserInfo, error) {
  140. // use userinfo endpoint for Google OIDC to get claims
  141. url := "https://openidconnect.googleapis.com/v1/userinfo"
  142. req, err := http.NewRequest("GET", url, nil)
  143. req.Header.Add("Authorization", "Bearer "+tok.AccessToken)
  144. client := &http.Client{}
  145. response, err := client.Do(req)
  146. if err != nil {
  147. return nil, fmt.Errorf("failed getting user info: %s", err.Error())
  148. }
  149. defer response.Body.Close()
  150. contents, err := ioutil.ReadAll(response.Body)
  151. if err != nil {
  152. return nil, fmt.Errorf("failed reading response body: %s", err.Error())
  153. }
  154. // parse contents into Google userinfo claims
  155. gInfo := &googleUserInfo{}
  156. err = json.Unmarshal(contents, &gInfo)
  157. return gInfo, nil
  158. }