Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

TT-13870 Fix POST update #4

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 47 additions & 5 deletions resource/crud.go
Original file line number Diff line number Diff line change
Expand Up @@ -136,12 +136,54 @@ func (res *Resource) findManyHandler(result interface{}, context *qor.Context) e
}

func (res *Resource) saveHandler(result interface{}, context *qor.Context) error {
if (context.GetDB().NewScope(result).PrimaryKeyZero() &&
res.HasPermission(roles.Create, context)) || // has create permission
res.HasPermission(roles.Update, context) { // has update permission
return context.GetDB().Save(result).Error
scope := context.GetDB().NewScope(result)
isPrimaryKeyZero := scope.PrimaryKeyZero()

if isPrimaryKeyZero {
// Create operation
if !res.HasPermission(roles.Create, context) {
return roles.ErrPermissionDenied
}

return context.GetDB().Create(result).Error
}
return roles.ErrPermissionDenied

// If we have a non-zero primary key, first check if it exists
var count int

primaryField := scope.PrimaryField()
if primaryField == nil {
return fmt.Errorf("no primary key field found")
}

query := fmt.Sprintf("%v = ?", scope.Quote(primaryField.DBName))
if err := context.GetDB().Model(result).Where(query, scope.PrimaryKeyValue()).Count(&count).Error; err != nil {
return err
}

// For creation attempts with existing ID
if context.Request != nil && context.Request.Method == "POST" {
if count > 0 {
return fmt.Errorf("record with primary key %v already exists", scope.PrimaryKeyValue())
}

if !res.HasPermission(roles.Create, context) {
return roles.ErrPermissionDenied
}

return context.GetDB().Create(result).Error
}

// Update operation
if !res.HasPermission(roles.Update, context) {
return roles.ErrPermissionDenied
}

if count == 0 {
return fmt.Errorf("record with primary key %v not found", scope.PrimaryKeyValue())
}

return context.GetDB().Save(result).Error
}

func (res *Resource) deleteHandler(result interface{}, context *qor.Context) error {
Expand Down
Loading