1
0
Fork 0
mirror of https://github.com/portainer/portainer.git synced 2025-07-21 14:29:40 +02:00
portainer/api/http/handler/webhooks/webhook_create.go
Chaim Lev-Ari db4a5292be
refactor(errors): reorganize errors (#3938)
* refactor(bolt): move ErrObjectNotFound to bolt

* refactor(http): move ErrUnauthorized to http package

* refactor(http): move ErrResourceAccessDenied to http errors

* refactor(http): move security errors to package

* refactor(users): move user errors to users package

* refactor(errors): move single errors to their package

* refactor(schedules): move schedule error to package

* refactor(http): move endpoint error to http package

* refactor(docker): move docker errors to package

* refactor(filesystem): move filesystem errors to package

* refactor(errors): remove portainer.Error

* style(chisel): reorder imports

* fix(stacks): remove portainer.Error
2020-07-08 09:57:52 +12:00

68 lines
2.1 KiB
Go

package webhooks
import (
"errors"
"net/http"
"github.com/asaskevich/govalidator"
"github.com/gofrs/uuid"
httperror "github.com/portainer/libhttp/error"
"github.com/portainer/libhttp/request"
"github.com/portainer/libhttp/response"
"github.com/portainer/portainer/api"
bolterrors "github.com/portainer/portainer/api/bolt/errors"
)
type webhookCreatePayload struct {
ResourceID string
EndpointID int
WebhookType int
}
func (payload *webhookCreatePayload) Validate(r *http.Request) error {
if govalidator.IsNull(payload.ResourceID) {
return errors.New("Invalid ResourceID")
}
if payload.EndpointID == 0 {
return errors.New("Invalid EndpointID")
}
if payload.WebhookType != 1 {
return errors.New("Invalid WebhookType")
}
return nil
}
func (handler *Handler) webhookCreate(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {
var payload webhookCreatePayload
err := request.DecodeAndValidateJSONPayload(r, &payload)
if err != nil {
return &httperror.HandlerError{http.StatusBadRequest, "Invalid request payload", err}
}
webhook, err := handler.DataStore.Webhook().WebhookByResourceID(payload.ResourceID)
if err != nil && err != bolterrors.ErrObjectNotFound {
return &httperror.HandlerError{http.StatusInternalServerError, "An error occurred retrieving webhooks from the database", err}
}
if webhook != nil {
return &httperror.HandlerError{http.StatusConflict, "A webhook for this resource already exists", errors.New("A webhook for this resource already exists")}
}
token, err := uuid.NewV4()
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Error creating unique token", err}
}
webhook = &portainer.Webhook{
Token: token.String(),
ResourceID: payload.ResourceID,
EndpointID: portainer.EndpointID(payload.EndpointID),
WebhookType: portainer.WebhookType(payload.WebhookType),
}
err = handler.DataStore.Webhook().CreateWebhook(webhook)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to persist the webhook inside the database", err}
}
return response.JSON(w, webhook)
}