oauth_github_handler.go 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  1. package api
  2. import (
  3. "context"
  4. "fmt"
  5. "net/http"
  6. "strconv"
  7. "github.com/porter-dev/porter/internal/models"
  8. "github.com/go-chi/chi"
  9. "github.com/google/go-github/github"
  10. "github.com/porter-dev/porter/internal/oauth"
  11. "golang.org/x/oauth2"
  12. "github.com/porter-dev/porter/internal/models/integrations"
  13. )
  14. // HandleGithubOAuthStartUser starts the oauth2 flow for a user login request.
  15. func (app *App) HandleGithubOAuthStartUser(w http.ResponseWriter, r *http.Request) {
  16. state := oauth.CreateRandomState()
  17. err := app.populateOAuthSession(w, r, state, false)
  18. if err != nil {
  19. app.handleErrorDataRead(err, w)
  20. return
  21. }
  22. // specify access type offline to get a refresh token
  23. url := app.GithubConf.AuthCodeURL(state, oauth2.AccessTypeOnline)
  24. http.Redirect(w, r, url, 302)
  25. }
  26. // HandleGithubOAuthStartProject starts the oauth2 flow for a project repo request.
  27. // In this handler, the project id gets written to the session (along with the oauth
  28. // state param), so that the correct project id can be identified in the callback.
  29. func (app *App) HandleGithubOAuthStartProject(w http.ResponseWriter, r *http.Request) {
  30. state := oauth.CreateRandomState()
  31. err := app.populateOAuthSession(w, r, state, true)
  32. if err != nil {
  33. app.handleErrorDataRead(err, w)
  34. return
  35. }
  36. // specify access type offline to get a refresh token
  37. url := app.GithubConf.AuthCodeURL(state, oauth2.AccessTypeOffline)
  38. http.Redirect(w, r, url, 302)
  39. }
  40. // HandleGithubOAuthCallback verifies the callback request by checking that the
  41. // state parameter has not been modified, and validates the token.
  42. // There is a difference between the oauth flow when logging a user in, and when
  43. // linking a repository.
  44. //
  45. // When logging a user in, the access token gets stored in the session, and no refresh
  46. // token is requested. We store the access token in the session because a user can be
  47. // logged in multiple times with a single access token.
  48. //
  49. // NOTE: this user flow will likely be augmented with Dex, or entirely replaced with Dex.
  50. //
  51. // However, when linking a repository, the access token and refresh token are requested when
  52. // the flow has started. A project also gets linked to the session. After callback, a new
  53. // github config gets stored for the project, and the user will then get redirected to
  54. // a URL that allows them to select their repositories they'd like to link. We require a refresh
  55. // token because we need permanent access to the linked repository.
  56. func (app *App) HandleGithubOAuthCallback(w http.ResponseWriter, r *http.Request) {
  57. session, err := app.Store.Get(r, app.ServerConf.CookieName)
  58. if err != nil {
  59. app.handleErrorDataRead(err, w)
  60. return
  61. }
  62. if _, ok := session.Values["state"]; !ok {
  63. app.sendExternalError(
  64. err,
  65. http.StatusForbidden,
  66. HTTPError{
  67. Code: http.StatusForbidden,
  68. Errors: []string{
  69. "Could not read cookie: are cookies enabled?",
  70. },
  71. },
  72. w,
  73. )
  74. return
  75. }
  76. if r.URL.Query().Get("state") != session.Values["state"] {
  77. http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
  78. return
  79. }
  80. token, err := app.GithubConf.Exchange(oauth2.NoContext, r.URL.Query().Get("code"))
  81. if err != nil {
  82. http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
  83. return
  84. }
  85. if !token.Valid() {
  86. http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
  87. return
  88. }
  89. userID, _ := session.Values["user_id"].(uint)
  90. projID, _ := session.Values["project_id"].(uint)
  91. app.updateProjectFromToken(projID, userID, token)
  92. if session.Values["query_params"] != "" {
  93. http.Redirect(w, r, fmt.Sprintf("/dashboard?%s", session.Values["query_params"]), 302)
  94. } else {
  95. http.Redirect(w, r, "/dashboard", 302)
  96. }
  97. }
  98. func (app *App) populateOAuthSession(w http.ResponseWriter, r *http.Request, state string, isProject bool) error {
  99. session, err := app.Store.Get(r, app.ServerConf.CookieName)
  100. if err != nil {
  101. return err
  102. }
  103. // need state parameter to validate when redirected
  104. session.Values["state"] = state
  105. if isProject {
  106. // read the project id and add it to the session
  107. projID, err := strconv.ParseUint(chi.URLParam(r, "project_id"), 0, 64)
  108. if err != nil || projID == 0 {
  109. return fmt.Errorf("could not read project id")
  110. }
  111. session.Values["project_id"] = projID
  112. session.Values["query_params"] = r.URL.RawQuery
  113. }
  114. if err := session.Save(r, w); err != nil {
  115. app.Logger.Warn().Err(err)
  116. }
  117. return nil
  118. }
  119. func (app *App) upsertUserFromToken() error {
  120. return fmt.Errorf("UNIMPLEMENTED")
  121. }
  122. // updates a project's repository clients with the token information.
  123. func (app *App) updateProjectFromToken(projectID uint, userID uint, tok *oauth2.Token) error {
  124. // get the list of repositories that this token has access to
  125. client := github.NewClient(app.GithubConf.Client(oauth2.NoContext, tok))
  126. user, _, err := client.Users.Get(context.Background(), "")
  127. if err != nil {
  128. return err
  129. }
  130. oauthInt := &integrations.OAuthIntegration{
  131. Client: integrations.OAuthGithub,
  132. UserID: userID,
  133. ProjectID: projectID,
  134. AccessToken: []byte(tok.AccessToken),
  135. RefreshToken: []byte(tok.RefreshToken),
  136. }
  137. // create the oauth integration first
  138. oauthInt, err = app.Repo.OAuthIntegration.CreateOAuthIntegration(oauthInt)
  139. if err != nil {
  140. return err
  141. }
  142. // create the git repo
  143. gr := &models.GitRepo{
  144. ProjectID: projectID,
  145. RepoEntity: *user.Name,
  146. OAuthIntegrationID: oauthInt.ID,
  147. }
  148. gr, err = app.Repo.GitRepo.CreateGitRepo(gr)
  149. return err
  150. }