helpers.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package gitinstallation
  2. import (
  3. "net/http"
  4. "github.com/bradleyfalzon/ghinstallation"
  5. "github.com/google/go-github/github"
  6. "github.com/porter-dev/porter/api/server/shared/config"
  7. "github.com/porter-dev/porter/api/types"
  8. "github.com/porter-dev/porter/internal/models"
  9. "github.com/porter-dev/porter/internal/models/integrations"
  10. "github.com/porter-dev/porter/internal/oauth"
  11. "golang.org/x/oauth2"
  12. )
  13. // GetGithubAppOauthTokenFromRequest gets the GH oauth token from the request based on the currently
  14. // logged in user
  15. func GetGithubAppOauthTokenFromRequest(config *config.Config, r *http.Request) (*oauth2.Token, error) {
  16. // read the user from context
  17. user, _ := r.Context().Value(types.UserScope).(*models.User)
  18. getOAuthInt := config.Repo.GithubAppOAuthIntegration().ReadGithubAppOauthIntegration
  19. oauthInt, err := getOAuthInt(user.GithubAppIntegrationID)
  20. if err != nil {
  21. return nil, err
  22. }
  23. _, _, err = oauth.GetAccessToken(oauthInt.SharedOAuthModel,
  24. &config.GithubAppConf.Config,
  25. oauth.MakeUpdateGithubAppOauthIntegrationFunction(oauthInt, config.Repo),
  26. )
  27. if err != nil {
  28. // try again, in case the token got updated
  29. oauthInt2, err := getOAuthInt(user.GithubAppIntegrationID)
  30. if err != nil || oauthInt2.Expiry == oauthInt.Expiry {
  31. return nil, err
  32. }
  33. oauthInt.AccessToken = oauthInt2.AccessToken
  34. oauthInt.RefreshToken = oauthInt2.RefreshToken
  35. oauthInt.Expiry = oauthInt2.Expiry
  36. }
  37. return &oauth2.Token{
  38. AccessToken: string(oauthInt.AccessToken),
  39. RefreshToken: string(oauthInt.RefreshToken),
  40. Expiry: oauthInt.Expiry,
  41. TokenType: "Bearer",
  42. }, nil
  43. }
  44. // GetGithubAppClientFromRequest gets the github app installation id from the request and authenticates
  45. // using it and a private key file
  46. func GetGithubAppClientFromRequest(config *config.Config, r *http.Request) (*github.Client, error) {
  47. // get installation id from context
  48. ga, _ := r.Context().Value(types.GitInstallationScope).(*integrations.GithubAppInstallation)
  49. itr, err := ghinstallation.NewKeyFromFile(
  50. http.DefaultTransport,
  51. config.GithubAppConf.AppID,
  52. int64(ga.ID),
  53. config.GithubAppConf.SecretPath,
  54. )
  55. if err != nil {
  56. return nil, err
  57. }
  58. return github.NewClient(&http.Client{Transport: itr}), nil
  59. }