refactor: more refactoring of methods and move some validation to gorm
This commit is contained in:
parent
3e629cf46e
commit
302821d749
|
@ -74,19 +74,26 @@ func (s *AccountServiceDefault) AccountExists(id uint) (bool, *models.User, erro
|
|||
return true, model.(*models.User), nil // Ensure to assert the type correctly
|
||||
}
|
||||
|
||||
func (s AccountServiceDefault) CreateAccount(email string, password string) (*models.User, error) {
|
||||
var user models.User
|
||||
|
||||
func (s *AccountServiceDefault) HashPassword(password string) (string, error) {
|
||||
bytes, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return string(bytes), nil
|
||||
}
|
||||
|
||||
func (s *AccountServiceDefault) CreateAccount(email string, password string) (*models.User, error) {
|
||||
passwordHash, err := s.HashPassword(password)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
user.Email = email
|
||||
user.PasswordHash = string(bytes)
|
||||
user := models.User{
|
||||
Email: email,
|
||||
PasswordHash: passwordHash,
|
||||
}
|
||||
|
||||
result := s.db.Create(&user)
|
||||
|
||||
if result.Error != nil {
|
||||
return nil, result.Error
|
||||
}
|
||||
|
@ -99,14 +106,6 @@ func (s AccountServiceDefault) UpdateAccountName(userId uint, firstName string,
|
|||
|
||||
user.ID = userId
|
||||
|
||||
if len(firstName) == 0 {
|
||||
return errors.New("First name cannot be empty")
|
||||
}
|
||||
|
||||
if len(lastName) == 0 {
|
||||
return errors.New("Last name cannot be empty")
|
||||
}
|
||||
|
||||
result := s.db.Model(&models.User{}).Where(&user).Updates(&models.User{FirstName: firstName, LastName: lastName})
|
||||
|
||||
if result.Error != nil {
|
||||
|
@ -271,3 +270,10 @@ func (s AccountServiceDefault) PinByID(uploadId uint, accountID uint) error {
|
|||
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateName(firstName, lastName string) error {
|
||||
if len(firstName) == 0 || len(lastName) == 0 {
|
||||
return errors.New("first name and last name cannot be empty")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
|
|
@ -1,6 +1,7 @@
|
|||
package models
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"gorm.io/gorm"
|
||||
"time"
|
||||
)
|
||||
|
@ -18,3 +19,14 @@ type User struct {
|
|||
LastLogin *time.Time
|
||||
LastLoginIP string
|
||||
}
|
||||
|
||||
func (u *User) BeforeUpdate(tx *gorm.DB) error {
|
||||
if len(u.FirstName) == 0 {
|
||||
return errors.New("first name is empty")
|
||||
}
|
||||
|
||||
if len(u.LastName) == 0 {
|
||||
return errors.New("last name is empty")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue