refactor(handler): extract DoUpdate from UpdateWeb

This commit is contained in:
kolaente 2026-04-20 10:50:51 +02:00
parent be988d47e2
commit d677e40597
2 changed files with 40 additions and 37 deletions

View File

@ -134,3 +134,42 @@ func DoReadAll(_ context.Context, obj CObject, a web.Auth, search string, page,
events.DispatchPending(s)
return result, resultCount, total, nil
}
// DoUpdate runs the permission check + model Update + commit pipeline for a
// CObject. Framework-agnostic. Caller is responsible for body/path binding
// and validation before calling.
func DoUpdate(_ 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)
}
}()
canUpdate, err := obj.CanUpdate(s, a)
if err != nil {
_ = s.Rollback()
events.CleanupPending(s)
return err
}
if !canUpdate {
_ = s.Rollback()
events.CleanupPending(s)
log.Warningf("Tried to update while not having the permissions for it (User: %v)", a)
return echo.NewHTTPError(http.StatusForbidden, "Forbidden")
}
if err := obj.Update(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"
@ -57,43 +55,9 @@ func (c *WebHandler) UpdateWeb(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)
}
}()
canUpdate, err := currentStruct.CanUpdate(s, currentAuth)
if err != nil {
_ = s.Rollback()
events.CleanupPending(s)
if err := DoUpdate(ctx.Request().Context(), currentStruct, currentAuth); err != nil {
return err
}
if !canUpdate {
_ = s.Rollback()
events.CleanupPending(s)
log.Warningf("Tried to update while not having the permissions for it (User: %v)", currentAuth)
return echo.NewHTTPError(http.StatusForbidden, "Forbidden")
}
// Do the update
err = currentStruct.Update(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, currentStruct)
}