diff options
Diffstat (limited to 'customer/validators.go')
-rw-r--r-- | customer/validators.go | 59 |
1 files changed, 40 insertions, 19 deletions
diff --git a/customer/validators.go b/customer/validators.go index bfd244f..2a37394 100644 --- a/customer/validators.go +++ b/customer/validators.go @@ -29,8 +29,9 @@ import ( func validateContactField(field, value string, userId uint) error { if value != "" { var count int64 - err := db.Model(&CustomerContact{}). - Where(field + " = ? and user_id = ?", value, userId). + err := db.Model(&Customer{}). + //Select(""). + Where("user_id = ? and " + field + " = ?", userId, value). Count(&count). Error @@ -55,29 +56,15 @@ func validateContactField(field, value string, userId uint) error { return nil } -func (c *CustomerContact) validate() error { +func (c *Customer) validate() error { // trim whitespaces c.Name = strings.TrimSpace(c.Name) + c.Gstin = strings.TrimSpace(c.Gstin) + c.ContactName = strings.TrimSpace(c.Name) c.Phone = strings.TrimSpace(c.Phone) c.Email = strings.TrimSpace(c.Email) c.Website = strings.TrimSpace(c.Website) - var err error - for _, i := range [][]string{{"phone", c.Phone}, {"email", c.Email}, {"website", c.Website}} { - err = validateContactField(i[0], i[1], c.UserID) - if err != nil { - return err - } - } - - return nil -} - -func (c *Customer) validate() error { - // trim whitespaces - c.Name = strings.TrimSpace(c.Name) - c.Gstin = strings.TrimSpace(c.Gstin) - // don't validate if GSTIN is empty if c.Gstin != "" { // GSTIN regex validation @@ -103,5 +90,39 @@ func (c *Customer) validate() error { } } + var err error + for _, i := range [][]string{{"phone", c.Phone}, {"email", c.Email}, {"website", c.Website}} { + err = validateContactField(i[0], i[1], c.UserID) + if err != nil { + return err + } + } + + return nil +} + +func checkCustomerOwnership(customerId, userId uint) error { + var customer Customer + err := db. + Select("id", "user_id"). + Where("id = ?", customerId). + Find(&customer). + Error + + // TODO: handle potential errors + if err != nil { + return err + } + + // customer doesn't exist + if customer.ID == 0 { + return errors.ErrNotFound + } + + // user doesn't own this customer + if customer.UserID != userId { + return errors.ErrForbidden + } + return nil } |