oauth_google_handler.go 5.5 KB

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