oauth_github_handler.go 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  1. package api
  2. import (
  3. "context"
  4. "fmt"
  5. "net/http"
  6. "strconv"
  7. "github.com/porter-dev/porter/internal/models"
  8. "gorm.io/gorm"
  9. "github.com/go-chi/chi"
  10. "github.com/google/go-github/github"
  11. "github.com/porter-dev/porter/internal/oauth"
  12. "golang.org/x/oauth2"
  13. "github.com/porter-dev/porter/internal/models/integrations"
  14. )
  15. // HandleGithubOAuthStartUser starts the oauth2 flow for a user login request.
  16. func (app *App) HandleGithubOAuthStartUser(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.GithubUserConf.AuthCodeURL(state, oauth2.AccessTypeOnline)
  25. http.Redirect(w, r, url, 302)
  26. }
  27. // HandleGithubOAuthStartProject starts the oauth2 flow for a project repo request.
  28. // In this handler, the project id gets written to the session (along with the oauth
  29. // state param), so that the correct project id can be identified in the callback.
  30. func (app *App) HandleGithubOAuthStartProject(w http.ResponseWriter, r *http.Request) {
  31. state := oauth.CreateRandomState()
  32. err := app.populateOAuthSession(w, r, state, true)
  33. if err != nil {
  34. app.handleErrorDataRead(err, w)
  35. return
  36. }
  37. // specify access type offline to get a refresh token
  38. url := app.GithubProjectConf.AuthCodeURL(state, oauth2.AccessTypeOffline)
  39. http.Redirect(w, r, url, 302)
  40. }
  41. // HandleGithubOAuthCallback verifies the callback request by checking that the
  42. // state parameter has not been modified, and validates the token.
  43. // There is a difference between the oauth flow when logging a user in, and when
  44. // linking a repository.
  45. //
  46. // When logging a user in, the access token gets stored in the session, and no refresh
  47. // token is requested. We store the access token in the session because a user can be
  48. // logged in multiple times with a single access token.
  49. //
  50. // NOTE: this user flow will likely be augmented with Dex, or entirely replaced with Dex.
  51. //
  52. // However, when linking a repository, the access token and refresh token are requested when
  53. // the flow has started. A project also gets linked to the session. After callback, a new
  54. // github config gets stored for the project, and the user will then get redirected to
  55. // a URL that allows them to select their repositories they'd like to link. We require a refresh
  56. // token because we need permanent access to the linked repository.
  57. func (app *App) HandleGithubOAuthCallback(w http.ResponseWriter, r *http.Request) {
  58. session, err := app.Store.Get(r, app.ServerConf.CookieName)
  59. if err != nil {
  60. app.handleErrorDataRead(err, w)
  61. return
  62. }
  63. if _, ok := session.Values["state"]; !ok {
  64. app.sendExternalError(
  65. err,
  66. http.StatusForbidden,
  67. HTTPError{
  68. Code: http.StatusForbidden,
  69. Errors: []string{
  70. "Could not read cookie: are cookies enabled?",
  71. },
  72. },
  73. w,
  74. )
  75. return
  76. }
  77. if r.URL.Query().Get("state") != session.Values["state"] {
  78. http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
  79. return
  80. }
  81. token, err := app.GithubProjectConf.Exchange(oauth2.NoContext, r.URL.Query().Get("code"))
  82. if err != nil {
  83. http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
  84. return
  85. }
  86. if !token.Valid() {
  87. http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
  88. return
  89. }
  90. if session.Values["project_id"] != nil && session.Values["project_id"] != "" {
  91. userID, _ := session.Values["user_id"].(uint)
  92. projID, _ := session.Values["project_id"].(uint)
  93. app.updateProjectFromToken(projID, userID, token)
  94. } else {
  95. // otherwise, create the user if not exists
  96. user, err := app.upsertUserFromToken(token)
  97. if err != nil {
  98. http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
  99. return
  100. }
  101. // log the user in
  102. app.Logger.Info().Msgf("New user created: %d", user.ID)
  103. session.Values["authenticated"] = true
  104. session.Values["user_id"] = user.ID
  105. session.Values["email"] = user.Email
  106. session.Values["redirect"] = ""
  107. session.Save(r, w)
  108. }
  109. if session.Values["query_params"] != "" {
  110. http.Redirect(w, r, fmt.Sprintf("/dashboard?%s", session.Values["query_params"]), 302)
  111. } else {
  112. http.Redirect(w, r, "/dashboard", 302)
  113. }
  114. }
  115. func (app *App) populateOAuthSession(w http.ResponseWriter, r *http.Request, state string, isProject bool) error {
  116. session, err := app.Store.Get(r, app.ServerConf.CookieName)
  117. if err != nil {
  118. return err
  119. }
  120. // need state parameter to validate when redirected
  121. session.Values["state"] = state
  122. session.Values["query_params"] = r.URL.RawQuery
  123. if isProject {
  124. // read the project id and add it to the session
  125. projID, err := strconv.ParseUint(chi.URLParam(r, "project_id"), 0, 64)
  126. if err != nil || projID == 0 {
  127. return fmt.Errorf("could not read project id")
  128. }
  129. session.Values["project_id"] = uint(projID)
  130. }
  131. if err := session.Save(r, w); err != nil {
  132. app.Logger.Warn().Err(err)
  133. }
  134. return nil
  135. }
  136. func (app *App) upsertUserFromToken(tok *oauth2.Token) (*models.User, error) {
  137. // determine if the user already exists
  138. client := github.NewClient(app.GithubProjectConf.Client(oauth2.NoContext, tok))
  139. githubUser, _, err := client.Users.Get(context.Background(), "")
  140. if err != nil {
  141. return nil, err
  142. }
  143. user, err := app.Repo.User.ReadUserByGithubUserID(*githubUser.ID)
  144. // if the user does not exist, create new user
  145. if err != nil && err == gorm.ErrRecordNotFound {
  146. emails, _, err := client.Users.ListEmails(context.Background(), &github.ListOptions{})
  147. if err != nil {
  148. return nil, err
  149. }
  150. primary := ""
  151. // get the primary email
  152. for _, email := range emails {
  153. if email.GetPrimary() {
  154. primary = email.GetEmail()
  155. break
  156. }
  157. }
  158. if primary == "" {
  159. return nil, fmt.Errorf("github user must have an email")
  160. }
  161. user = &models.User{
  162. Email: primary,
  163. GithubUserID: githubUser.GetID(),
  164. }
  165. user, err = app.Repo.User.CreateUser(user)
  166. } else if err != nil {
  167. return nil, fmt.Errorf("unexpected error occurred:", err.Error())
  168. }
  169. return user, err
  170. }
  171. // updates a project's repository clients with the token information.
  172. func (app *App) updateProjectFromToken(projectID uint, userID uint, tok *oauth2.Token) error {
  173. // get the list of repositories that this token has access to
  174. client := github.NewClient(app.GithubProjectConf.Client(oauth2.NoContext, tok))
  175. user, _, err := client.Users.Get(context.Background(), "")
  176. if err != nil {
  177. return err
  178. }
  179. oauthInt := &integrations.OAuthIntegration{
  180. Client: integrations.OAuthGithub,
  181. UserID: userID,
  182. ProjectID: projectID,
  183. AccessToken: []byte(tok.AccessToken),
  184. RefreshToken: []byte(tok.RefreshToken),
  185. }
  186. // create the oauth integration first
  187. oauthInt, err = app.Repo.OAuthIntegration.CreateOAuthIntegration(oauthInt)
  188. if err != nil {
  189. return err
  190. }
  191. // create the git repo
  192. gr := &models.GitRepo{
  193. ProjectID: projectID,
  194. RepoEntity: *user.Login,
  195. OAuthIntegrationID: oauthInt.ID,
  196. }
  197. gr, err = app.Repo.GitRepo.CreateGitRepo(gr)
  198. return err
  199. }