oauth_google_handler.go 5.3 KB

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