2
0

webhook.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. package gitinstallation
  2. import (
  3. "net/http"
  4. "github.com/google/go-github/v41/github"
  5. "github.com/porter-dev/porter/api/server/authz"
  6. "github.com/porter-dev/porter/api/server/handlers"
  7. "github.com/porter-dev/porter/api/server/shared"
  8. "github.com/porter-dev/porter/api/server/shared/apierrors"
  9. "github.com/porter-dev/porter/api/server/shared/config"
  10. "gorm.io/gorm"
  11. ints "github.com/porter-dev/porter/internal/models/integrations"
  12. )
  13. type GithubAppWebhookHandler struct {
  14. handlers.PorterHandlerReadWriter
  15. authz.KubernetesAgentGetter
  16. }
  17. func NewGithubAppWebhookHandler(
  18. config *config.Config,
  19. decoderValidator shared.RequestDecoderValidator,
  20. writer shared.ResultWriter,
  21. ) *GithubAppWebhookHandler {
  22. return &GithubAppWebhookHandler{
  23. PorterHandlerReadWriter: handlers.NewDefaultPorterHandler(config, decoderValidator, writer),
  24. }
  25. }
  26. func (c *GithubAppWebhookHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  27. payload, err := github.ValidatePayload(r, []byte(c.Config().GithubAppConf.WebhookSecret))
  28. if err != nil {
  29. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  30. return
  31. }
  32. event, err := github.ParseWebHook(github.WebHookType(r), payload)
  33. if err != nil {
  34. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  35. return
  36. }
  37. switch e := event.(type) {
  38. case *github.InstallationEvent:
  39. if *e.Action == "created" {
  40. _, err := c.Repo().GithubAppInstallation().ReadGithubAppInstallationByAccountID(*e.Installation.Account.ID)
  41. if err != nil && err == gorm.ErrRecordNotFound {
  42. // insert account/installation pair into database
  43. _, err := c.Repo().GithubAppInstallation().CreateGithubAppInstallation(&ints.GithubAppInstallation{
  44. AccountID: *e.Installation.Account.ID,
  45. InstallationID: *e.Installation.ID,
  46. })
  47. if err != nil {
  48. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  49. }
  50. return
  51. } else if err != nil {
  52. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  53. return
  54. }
  55. }
  56. if *e.Action == "deleted" {
  57. err := c.Repo().GithubAppInstallation().DeleteGithubAppInstallationByAccountID(*e.Installation.Account.ID)
  58. if err != nil {
  59. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  60. return
  61. }
  62. }
  63. }
  64. }