oauth_github_handler.go 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  1. package api
  2. import (
  3. "context"
  4. "fmt"
  5. "net/http"
  6. "net/url"
  7. "strconv"
  8. "strings"
  9. "github.com/porter-dev/porter/internal/models"
  10. "gorm.io/gorm"
  11. "github.com/go-chi/chi"
  12. "github.com/google/go-github/github"
  13. "github.com/porter-dev/porter/internal/oauth"
  14. "golang.org/x/oauth2"
  15. "github.com/porter-dev/porter/internal/models/integrations"
  16. segment "gopkg.in/segmentio/analytics-go.v3"
  17. )
  18. // HandleGithubOAuthStartUser starts the oauth2 flow for a user login request.
  19. func (app *App) HandleGithubOAuthStartUser(w http.ResponseWriter, r *http.Request) {
  20. state := oauth.CreateRandomState()
  21. err := app.populateOAuthSession(w, r, state, false)
  22. if err != nil {
  23. app.handleErrorDataRead(err, w)
  24. return
  25. }
  26. // specify access type offline to get a refresh token
  27. url := app.GithubUserConf.AuthCodeURL(state, oauth2.AccessTypeOnline)
  28. http.Redirect(w, r, url, 302)
  29. }
  30. // HandleGithubOAuthStartProject starts the oauth2 flow for a project repo request.
  31. // In this handler, the project id gets written to the session (along with the oauth
  32. // state param), so that the correct project id can be identified in the callback.
  33. func (app *App) HandleGithubOAuthStartProject(w http.ResponseWriter, r *http.Request) {
  34. state := oauth.CreateRandomState()
  35. err := app.populateOAuthSession(w, r, state, true)
  36. if err != nil {
  37. app.handleErrorDataRead(err, w)
  38. return
  39. }
  40. // specify access type offline to get a refresh token
  41. url := app.GithubProjectConf.AuthCodeURL(state, oauth2.AccessTypeOffline)
  42. http.Redirect(w, r, url, 302)
  43. }
  44. // HandleGithubOAuthCallback verifies the callback request by checking that the
  45. // state parameter has not been modified, and validates the token.
  46. // There is a difference between the oauth flow when logging a user in, and when
  47. // linking a repository.
  48. //
  49. // When logging a user in, the access token gets stored in the session, and no refresh
  50. // token is requested. We store the access token in the session because a user can be
  51. // logged in multiple times with a single access token.
  52. //
  53. // NOTE: this user flow will likely be augmented with Dex, or entirely replaced with Dex.
  54. //
  55. // However, when linking a repository, the access token and refresh token are requested when
  56. // the flow has started. A project also gets linked to the session. After callback, a new
  57. // github config gets stored for the project, and the user will then get redirected to
  58. // a URL that allows them to select their repositories they'd like to link. We require a refresh
  59. // token because we need permanent access to the linked repository.
  60. func (app *App) HandleGithubOAuthCallback(w http.ResponseWriter, r *http.Request) {
  61. session, err := app.Store.Get(r, app.ServerConf.CookieName)
  62. if err != nil {
  63. app.handleErrorDataRead(err, w)
  64. return
  65. }
  66. if _, ok := session.Values["state"]; !ok {
  67. app.sendExternalError(
  68. err,
  69. http.StatusForbidden,
  70. HTTPError{
  71. Code: http.StatusForbidden,
  72. Errors: []string{
  73. "Could not read cookie: are cookies enabled?",
  74. },
  75. },
  76. w,
  77. )
  78. return
  79. }
  80. if r.URL.Query().Get("state") != session.Values["state"] {
  81. http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
  82. return
  83. }
  84. token, err := app.GithubProjectConf.Exchange(oauth2.NoContext, r.URL.Query().Get("code"))
  85. if err != nil {
  86. http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
  87. return
  88. }
  89. if !token.Valid() {
  90. http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
  91. return
  92. }
  93. if session.Values["project_id"] != nil && session.Values["project_id"] != "" {
  94. userID, _ := session.Values["user_id"].(uint)
  95. projID, _ := session.Values["project_id"].(uint)
  96. app.updateProjectFromToken(projID, userID, token)
  97. } else {
  98. // otherwise, create the user if not exists
  99. user, err := app.upsertUserFromToken(token)
  100. if err != nil && strings.Contains(err.Error(), "already registered") {
  101. http.Redirect(w, r, "/login?error="+url.QueryEscape(err.Error()), 302)
  102. return
  103. } else if err != nil {
  104. http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
  105. return
  106. }
  107. // send to segment
  108. userId := fmt.Sprintf("%v", user.ID)
  109. app.segmentClient.Identify(userId, user.Email, true)
  110. app.segmentClient.Track(userId, "New User", segment.NewProperties().Set("email", user.Email))
  111. // log the user in
  112. app.Logger.Info().Msgf("New user created: %d", user.ID)
  113. session.Values["authenticated"] = true
  114. session.Values["user_id"] = user.ID
  115. session.Values["email"] = user.Email
  116. session.Values["redirect"] = ""
  117. session.Save(r, w)
  118. }
  119. if session.Values["query_params"] != "" {
  120. http.Redirect(w, r, fmt.Sprintf("/dashboard?%s", session.Values["query_params"]), 302)
  121. } else {
  122. http.Redirect(w, r, "/dashboard", 302)
  123. }
  124. }
  125. func (app *App) populateOAuthSession(w http.ResponseWriter, r *http.Request, state string, isProject bool) error {
  126. session, err := app.Store.Get(r, app.ServerConf.CookieName)
  127. if err != nil {
  128. return err
  129. }
  130. // need state parameter to validate when redirected
  131. session.Values["state"] = state
  132. session.Values["query_params"] = r.URL.RawQuery
  133. if isProject {
  134. // read the project id and add it to the session
  135. projID, err := strconv.ParseUint(chi.URLParam(r, "project_id"), 0, 64)
  136. if err != nil || projID == 0 {
  137. return fmt.Errorf("could not read project id")
  138. }
  139. session.Values["project_id"] = uint(projID)
  140. }
  141. if err := session.Save(r, w); err != nil {
  142. app.Logger.Warn().Err(err)
  143. }
  144. return nil
  145. }
  146. func (app *App) upsertUserFromToken(tok *oauth2.Token) (*models.User, error) {
  147. // determine if the user already exists
  148. client := github.NewClient(app.GithubProjectConf.Client(oauth2.NoContext, tok))
  149. githubUser, _, err := client.Users.Get(context.Background(), "")
  150. if err != nil {
  151. return nil, err
  152. }
  153. user, err := app.Repo.User.ReadUserByGithubUserID(*githubUser.ID)
  154. // if the user does not exist, create new user
  155. if err != nil && err == gorm.ErrRecordNotFound {
  156. emails, _, err := client.Users.ListEmails(context.Background(), &github.ListOptions{})
  157. if err != nil {
  158. return nil, err
  159. }
  160. primary := ""
  161. verified := false
  162. // get the primary email
  163. for _, email := range emails {
  164. if email.GetPrimary() {
  165. primary = email.GetEmail()
  166. verified = email.GetVerified()
  167. break
  168. }
  169. }
  170. if primary == "" {
  171. return nil, fmt.Errorf("github user must have an email")
  172. }
  173. // check if a user with that email address already exists
  174. _, err = app.Repo.User.ReadUserByEmail(primary)
  175. if err == gorm.ErrRecordNotFound {
  176. user = &models.User{
  177. Email: primary,
  178. EmailVerified: verified,
  179. GithubUserID: githubUser.GetID(),
  180. }
  181. user, err = app.Repo.User.CreateUser(user)
  182. if err != nil {
  183. return nil, err
  184. }
  185. } else if err == nil {
  186. return nil, fmt.Errorf("email already registered")
  187. } else if err != nil {
  188. return nil, err
  189. }
  190. } else if err != nil {
  191. return nil, fmt.Errorf("unexpected error occurred:%s", err.Error())
  192. }
  193. return user, nil
  194. }
  195. // updates a project's repository clients with the token information.
  196. func (app *App) updateProjectFromToken(projectID uint, userID uint, tok *oauth2.Token) error {
  197. // get the list of repositories that this token has access to
  198. client := github.NewClient(app.GithubProjectConf.Client(oauth2.NoContext, tok))
  199. user, _, err := client.Users.Get(context.Background(), "")
  200. if err != nil {
  201. return err
  202. }
  203. oauthInt := &integrations.OAuthIntegration{
  204. SharedOAuthModel: integrations.SharedOAuthModel{
  205. AccessToken: []byte(tok.AccessToken),
  206. RefreshToken: []byte(tok.RefreshToken),
  207. },
  208. Client: integrations.OAuthGithub,
  209. UserID: userID,
  210. ProjectID: projectID,
  211. }
  212. // create the oauth integration first
  213. oauthInt, err = app.Repo.OAuthIntegration.CreateOAuthIntegration(oauthInt)
  214. if err != nil {
  215. return err
  216. }
  217. // create the git repo
  218. gr := &models.GitRepo{
  219. ProjectID: projectID,
  220. RepoEntity: *user.Login,
  221. OAuthIntegrationID: oauthInt.ID,
  222. }
  223. gr, err = app.Repo.GitRepo.CreateGitRepo(gr)
  224. return err
  225. }
  226. // HandleGithubAppOAuthCallback handles the oauth callback from the GitHub app oauth flow
  227. // this basically just involves generating an access token and then linking it to the current user
  228. func (app *App) HandleGithubAppOAuthCallback(w http.ResponseWriter, r *http.Request) {
  229. session, err := app.Store.Get(r, app.ServerConf.CookieName)
  230. if err != nil {
  231. app.handleErrorDataRead(err, w)
  232. return
  233. }
  234. if _, ok := session.Values["state"]; !ok {
  235. app.sendExternalError(
  236. err,
  237. http.StatusForbidden,
  238. HTTPError{
  239. Code: http.StatusForbidden,
  240. Errors: []string{
  241. "Could not read cookie: are cookies enabled?",
  242. },
  243. },
  244. w,
  245. )
  246. return
  247. }
  248. if r.URL.Query().Get("state") != session.Values["state"] {
  249. if session.Values["query_params"] != "" {
  250. http.Redirect(w, r, fmt.Sprintf("/dashboard?%s", session.Values["query_params"]), 302)
  251. } else {
  252. http.Redirect(w, r, "/dashboard", 302)
  253. }
  254. return
  255. }
  256. token, err := app.GithubAppConf.Exchange(oauth2.NoContext, r.URL.Query().Get("code"))
  257. if err != nil || !token.Valid() {
  258. if session.Values["query_params"] != "" {
  259. http.Redirect(w, r, fmt.Sprintf("/dashboard?%s", session.Values["query_params"]), 302)
  260. } else {
  261. http.Redirect(w, r, "/dashboard", 302)
  262. }
  263. return
  264. }
  265. userID, err := app.getUserIDFromRequest(r)
  266. if err != nil {
  267. app.handleErrorInternal(err, w)
  268. return
  269. }
  270. user, err := app.Repo.User.ReadUser(userID)
  271. if err != nil {
  272. app.handleErrorInternal(err, w)
  273. return
  274. }
  275. oauthInt := &integrations.GithubAppOAuthIntegration{
  276. SharedOAuthModel: integrations.SharedOAuthModel{
  277. AccessToken: []byte(token.AccessToken),
  278. RefreshToken: []byte(token.RefreshToken),
  279. },
  280. UserID: user.ID,
  281. }
  282. oauthInt, err = app.Repo.GithubAppOAuthIntegration.CreateGithubAppOAuthIntegration(oauthInt)
  283. if err != nil {
  284. app.handleErrorInternal(err, w)
  285. return
  286. }
  287. user.GithubAppIntegrationID = oauthInt.ID
  288. user, err = app.Repo.User.UpdateUser(user)
  289. if err != nil {
  290. app.handleErrorInternal(err, w)
  291. return
  292. }
  293. if session.Values["query_params"] != "" {
  294. http.Redirect(w, r, fmt.Sprintf("/dashboard?%s", session.Values["query_params"]), 302)
  295. } else {
  296. http.Redirect(w, r, "/dashboard", 302)
  297. }
  298. }