get_accounts.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. package gitinstallation
  2. import (
  3. "context"
  4. "net/http"
  5. "sort"
  6. "github.com/google/go-github/github"
  7. "github.com/porter-dev/porter/api/server/authz"
  8. "github.com/porter-dev/porter/api/server/handlers"
  9. "github.com/porter-dev/porter/api/server/shared"
  10. "github.com/porter-dev/porter/api/server/shared/apierrors"
  11. "github.com/porter-dev/porter/api/server/shared/config"
  12. "github.com/porter-dev/porter/api/types"
  13. "golang.org/x/oauth2"
  14. "gorm.io/gorm"
  15. )
  16. type GetGithubAppAccountsHandler struct {
  17. handlers.PorterHandlerReadWriter
  18. authz.KubernetesAgentGetter
  19. }
  20. func NewGetGithubAppAccountsHandler(
  21. config *config.Config,
  22. decoderValidator shared.RequestDecoderValidator,
  23. writer shared.ResultWriter,
  24. ) *GetGithubAppAccountsHandler {
  25. return &GetGithubAppAccountsHandler{
  26. PorterHandlerReadWriter: handlers.NewDefaultPorterHandler(config, decoderValidator, writer),
  27. }
  28. }
  29. func (c *GetGithubAppAccountsHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  30. tok, err := GetGithubAppOauthTokenFromRequest(c.Config(), r)
  31. if err != nil {
  32. c.HandleAPIError(w, r, apierrors.NewErrForbidden(err))
  33. return
  34. }
  35. client := github.NewClient(c.Config().GithubAppConf.Client(oauth2.NoContext, tok))
  36. res := &types.GetGithubAppAccountsResponse{}
  37. for {
  38. orgs, pages, err := client.Organizations.List(context.Background(), "", &github.ListOptions{
  39. PerPage: 100,
  40. Page: 1,
  41. })
  42. if err != nil {
  43. continue
  44. }
  45. for _, org := range orgs {
  46. res.Accounts = append(res.Accounts, *org.Login)
  47. }
  48. if pages.NextPage == 0 {
  49. break
  50. }
  51. }
  52. authUser, _, err := client.Users.Get(context.Background(), "")
  53. if err != nil {
  54. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  55. return
  56. }
  57. res.Username = *authUser.Login
  58. // check if user has app installed in their account
  59. installation, err := c.Repo().GithubAppInstallation().ReadGithubAppInstallationByAccountID(*authUser.ID)
  60. if err != nil && err != gorm.ErrRecordNotFound {
  61. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  62. return
  63. }
  64. if installation != nil {
  65. res.Accounts = append(res.Accounts, *authUser.Login)
  66. }
  67. sort.Strings(res.Accounts)
  68. c.WriteResult(w, r, res)
  69. }