From 076dcc7633fd0537c0255a98a31a59ca6f5d9de4 Mon Sep 17 00:00:00 2001 From: Vidhu Kant Sharma Date: Sun, 3 Sep 2023 20:31:56 +0530 Subject: user can only access data generated by the same user now --- item/validators.go | 72 +++++++++++++++++++++++++++++++++++++++--------------- 1 file changed, 52 insertions(+), 20 deletions(-) (limited to 'item/validators.go') diff --git a/item/validators.go b/item/validators.go index 996a5d7..e931843 100644 --- a/item/validators.go +++ b/item/validators.go @@ -51,26 +51,6 @@ func (b *Brand) validate() error { return nil } -func checkIfBrandExists(id, userId uint) error { - // check if brand id is valid and is owned by user - var count int64 - err := db.Model(&Brand{}). - Select("id"). - Where("id = ? and user_id = ?", id, userId). - Count(&count). - Error - - if err != nil { - return err - } - - if count == 0 { - return errors.ErrBrandNotFound - } - - return nil -} - func (i *SavedItem) validate() error { // trim whitespaces i.Name = strings.TrimSpace(i.Name) @@ -109,3 +89,55 @@ func (i *SavedItem) validate() error { return nil } + +func checkBrandOwnership(brandId, userId uint) error { + var brand Brand + err := db. + Select("id", "user_id"). + Where("id = ?", brandId). + Find(&brand). + Error + + // TODO: handle potential errors + if err != nil { + return err + } + + // brand doesn't exist + if brand.ID == 0 { + return errors.ErrBrandNotFound + } + + // user doesn't own this brand + if brand.UserID != userId { + return errors.ErrForbidden + } + + return nil +} + +func checkItemOwnership(itemId, userId uint) error { + var item SavedItem + err := db. + Select("id", "user_id"). + Where("id = ?", itemId). + Find(&item). + Error + + // TODO: handle potential errors + if err != nil { + return err + } + + // item doesn't exist + if item.ID == 0 { + return errors.ErrNotFound + } + + // user doesn't own this item + if item.UserID != userId { + return errors.ErrForbidden + } + + return nil +} -- cgit v1.2.3