From 48845b9e703756471a98f8b1f1edaa2313763df4 Mon Sep 17 00:00:00 2001 From: Vidhu Kant Sharma Date: Mon, 9 Oct 2023 22:11:16 +0530 Subject: checking user while adding and removing invoice items --- invoice/service.go | 45 ++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 44 insertions(+), 1 deletion(-) (limited to 'invoice/service.go') diff --git a/invoice/service.go b/invoice/service.go index cfb873f..099f6a0 100644 --- a/invoice/service.go +++ b/invoice/service.go @@ -22,7 +22,7 @@ import ( ) func getInvoice(invoice *Invoice, id uint) error { - res := db.Preload("BillingAddress").Preload("ShippingAddress").Find(&invoice, id) + res := db.Preload("BillingAddress").Preload("ShippingAddress").Preload("Items").Find(&invoice, id) // TODO: handle potential errors if res.Error != nil { @@ -75,6 +75,49 @@ func (i *Invoice) del() error { return nil } +// also checks for ownership +func getItemInvoice(itemId, userId uint) (uint, error) { + var invoiceId uint + res := db. + Model(&InvoiceItem{}). + Select("invoice_id"). + Where("id = ?", itemId). + Find(&invoiceId) + + // TODO: handle potential errors + if res.Error != nil { + return invoiceId, res.Error + } + + if res.RowsAffected == 0 { + return invoiceId, e.ErrNotFound + } + + err := checkInvoiceOwnership(invoiceId, userId) + + if err != nil { + return invoiceId, err + } + + return invoiceId, nil +} + +func (i *InvoiceItem) del() error { + res := db.Delete(i) + + // TODO: handle potential errors + if res.Error != nil { + return res.Error + } + + // returns 404 if either row doesn't exist or if the user doesn't own it + if res.RowsAffected == 0 { + return e.ErrNotFound + } + + return nil +} + func (i *InvoiceItem) upsert() error { res := db.Save(i) // TODO: handle potential errors -- cgit v1.2.3