oauth_github_handler.go 5.1 KB

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