THIS IS A TEST INSTANCE ONLY! REPOSITORIES CAN BE DELETED AT ANY TIME!

This is Gitea test Portainer repository mirror from Github
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

67 lines
2.0 KiB

  1. package webhooks
  2. import (
  3. "net/http"
  4. "github.com/asaskevich/govalidator"
  5. "github.com/gofrs/uuid"
  6. httperror "github.com/portainer/libhttp/error"
  7. "github.com/portainer/libhttp/request"
  8. "github.com/portainer/libhttp/response"
  9. "github.com/portainer/portainer/api"
  10. )
  11. type webhookCreatePayload struct {
  12. ResourceID string
  13. EndpointID int
  14. WebhookType int
  15. }
  16. func (payload *webhookCreatePayload) Validate(r *http.Request) error {
  17. if govalidator.IsNull(payload.ResourceID) {
  18. return portainer.Error("Invalid ResourceID")
  19. }
  20. if payload.EndpointID == 0 {
  21. return portainer.Error("Invalid EndpointID")
  22. }
  23. if payload.WebhookType != 1 {
  24. return portainer.Error("Invalid WebhookType")
  25. }
  26. return nil
  27. }
  28. func (handler *Handler) webhookCreate(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {
  29. var payload webhookCreatePayload
  30. err := request.DecodeAndValidateJSONPayload(r, &payload)
  31. if err != nil {
  32. return &httperror.HandlerError{http.StatusBadRequest, "Invalid request payload", err}
  33. }
  34. webhook, err := handler.WebhookService.WebhookByResourceID(payload.ResourceID)
  35. if err != nil && err != portainer.ErrObjectNotFound {
  36. return &httperror.HandlerError{http.StatusInternalServerError, "An error occurred retrieving webhooks from the database", err}
  37. }
  38. if webhook != nil {
  39. return &httperror.HandlerError{http.StatusConflict, "A webhook for this resource already exists", portainer.ErrWebhookAlreadyExists}
  40. }
  41. token, err := uuid.NewV4()
  42. if err != nil {
  43. return &httperror.HandlerError{http.StatusInternalServerError, "Error creating unique token", err}
  44. }
  45. webhook = &portainer.Webhook{
  46. Token: token.String(),
  47. ResourceID: payload.ResourceID,
  48. EndpointID: portainer.EndpointID(payload.EndpointID),
  49. WebhookType: portainer.WebhookType(payload.WebhookType),
  50. }
  51. err = handler.WebhookService.CreateWebhook(webhook)
  52. if err != nil {
  53. return &httperror.HandlerError{http.StatusInternalServerError, "Unable to persist the webhook inside the database", err}
  54. }
  55. return response.JSON(w, webhook)
  56. }