refactor(handler): extract DoDelete from DeleteWeb

This commit is contained in:
kolaente 2026-04-20 10:52:08 +02:00 committed by kolaente
parent 1f4471c38f
commit 939381fb12
2 changed files with 40 additions and 36 deletions

View File

@ -173,3 +173,42 @@ func DoUpdate(_ context.Context, obj CObject, a web.Auth) error {
events.DispatchPending(s)
return nil
}
// DoDelete runs the permission check + model Delete + commit pipeline for a
// CObject. Framework-agnostic. Caller is responsible for path binding before
// calling.
func DoDelete(_ context.Context, obj CObject, a web.Auth) error {
s := db.NewSession()
defer func() {
if err := s.Close(); err != nil {
log.Errorf("Could not close session: %s", err)
}
}()
canDelete, err := obj.CanDelete(s, a)
if err != nil {
_ = s.Rollback()
events.CleanupPending(s)
return err
}
if !canDelete {
_ = s.Rollback()
events.CleanupPending(s)
log.Warningf("Tried to delete while not having the permissions for it (User: %v)", a)
return echo.NewHTTPError(http.StatusForbidden, "Forbidden")
}
if err := obj.Delete(s, a); err != nil {
_ = s.Rollback()
events.CleanupPending(s)
return err
}
if err := s.Commit(); err != nil {
events.CleanupPending(s)
return err
}
events.DispatchPending(s)
return nil
}

View File

@ -21,8 +21,6 @@ import (
"fmt"
"net/http"
"code.vikunja.io/api/pkg/db"
"code.vikunja.io/api/pkg/events"
"code.vikunja.io/api/pkg/log"
"code.vikunja.io/api/pkg/models"
"code.vikunja.io/api/pkg/modules/auth"
@ -56,42 +54,9 @@ func (c *WebHandler) DeleteWeb(ctx *echo.Context) error {
return echo.NewHTTPError(http.StatusInternalServerError, "Could not determine the current user.").Wrap(err)
}
// Create the db session
s := db.NewSession()
defer func() {
err = s.Close()
if err != nil {
log.Errorf("Could not close session: %s", err)
}
}()
canDelete, err := currentStruct.CanDelete(s, currentAuth)
if err != nil {
_ = s.Rollback()
events.CleanupPending(s)
if err := DoDelete(ctx.Request().Context(), currentStruct, currentAuth); err != nil {
return err
}
if !canDelete {
_ = s.Rollback()
events.CleanupPending(s)
log.Warningf("Tried to delete while not having the permissions for it (User: %v)", currentAuth)
return echo.NewHTTPError(http.StatusForbidden, "Forbidden")
}
err = currentStruct.Delete(s, currentAuth)
if err != nil {
_ = s.Rollback()
events.CleanupPending(s)
return err
}
err = s.Commit()
if err != nil {
events.CleanupPending(s)
return err
}
events.DispatchPending(s)
return ctx.JSON(http.StatusOK, message{"Successfully deleted."})
}