oauth_github_handler.go 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  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. // TODO -- custom redirect URI
  92. http.Redirect(w, r, "/", 302)
  93. }
  94. func (app *App) populateOAuthSession(w http.ResponseWriter, r *http.Request, state string, isProject bool) error {
  95. session, err := app.store.Get(r, app.cookieName)
  96. if err != nil {
  97. return err
  98. }
  99. // need state parameter to validate when redirected
  100. session.Values["state"] = state
  101. if isProject {
  102. // read the project id and add it to the session
  103. projID, err := strconv.ParseUint(chi.URLParam(r, "project_id"), 0, 64)
  104. if err != nil || projID == 0 {
  105. return fmt.Errorf("could not read project id")
  106. }
  107. session.Values["project_id"] = projID
  108. }
  109. if err := session.Save(r, w); err != nil {
  110. app.logger.Warn().Err(err)
  111. }
  112. return nil
  113. }
  114. func (app *App) upsertUserFromToken() error {
  115. return fmt.Errorf("UNIMPLEMENTED")
  116. }
  117. // updates a project's repository clients with the token information.
  118. func (app *App) updateProjectFromToken(projectID uint, userID uint, tok *oauth2.Token) error {
  119. // get the list of repositories that this token has access to
  120. client := github.NewClient(app.GithubConfig.Client(oauth2.NoContext, tok))
  121. user, _, err := client.Users.Get(context.Background(), "")
  122. if err != nil {
  123. return err
  124. }
  125. repoClient := &models.RepoClient{
  126. ProjectID: projectID,
  127. UserID: userID,
  128. RepoUserID: uint(user.GetID()),
  129. Kind: models.RepoClientGithub,
  130. AccessToken: tok.AccessToken,
  131. RefreshToken: tok.RefreshToken,
  132. }
  133. repoClient, err = app.repo.RepoClient.CreateRepoClient(repoClient)
  134. if err != nil {
  135. return err
  136. }
  137. return nil
  138. }