// Checks if a user with that email already exists in the database. If it does, // it returns an error, else it hashes the password, saves the new user // and returns the user. func (s *userService) Create(user *models.User) error { var err error user.Username = s.SanitizeUsername(user.Username) result, err := s.FindByUsername(user.Username) if err != nil { return err } else if result != nil { return DuplicateUsernameError } hashedPassword, err := s.EncryptPassword(user.Password) if err != nil { return err } user.Password = string(hashedPassword) user.Status = int(Enabled) err = s.db.Create(&user).Error if err != nil { return err } return nil }
// Edit user modifies the basic user's models attributes. The function checks // if the username changed and if it needs to check if the username is already // taken. func (s *userService) Edit(newUser *models.User) error { user, err := s.FindById(newUser.Id) newUser.Username = s.SanitizeUsername(newUser.Username) if err != nil { return err } else if user == nil { return nil } if user.Username != newUser.Username { duplicateUser, err := s.FindByUsername(newUser.Username) if err != nil { return err } else if duplicateUser != nil { return DuplicateUsernameError } } user.Username = newUser.Username user.FirstName = newUser.FirstName user.LastName = newUser.LastName user.Email = newUser.Email user.Status = newUser.Status user.IsAdmin = newUser.IsAdmin user.IsTeacher = newUser.IsTeacher return s.db.Save(&user).Error }