功能:增加平台账号管理与管理员保护
This commit is contained in:
@@ -113,12 +113,59 @@ func (s *UserService) Create(username, password, nickname, role string, merchant
|
||||
}
|
||||
|
||||
func (s *UserService) UpdateStatus(id uint, status int) error {
|
||||
res := s.db.Model(&model.User{}).Where("id = ?", id).Update("status", status)
|
||||
if res.Error != nil {
|
||||
return res.Error
|
||||
if status != 0 && status != 1 {
|
||||
return errors.New("用户状态无效")
|
||||
}
|
||||
if res.RowsAffected == 0 {
|
||||
return s.db.Transaction(func(tx *gorm.DB) error {
|
||||
var user model.User
|
||||
if err := tx.First(&user, id).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return errors.New("用户不存在")
|
||||
}
|
||||
return err
|
||||
}
|
||||
if user.Role == model.RoleAdmin && user.Status == 1 && status == 0 {
|
||||
var admins int64
|
||||
if err := tx.Model(&model.User{}).Where("role = ? AND status = ?", model.RoleAdmin, 1).Count(&admins).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if admins <= 1 {
|
||||
return errors.New("至少保留一个启用的平台管理员")
|
||||
}
|
||||
}
|
||||
return tx.Model(&user).Update("status", status).Error
|
||||
})
|
||||
}
|
||||
|
||||
// Delete removes a platform account and its merchant memberships. It protects the current
|
||||
// account and the final enabled platform administrator so the platform cannot be locked out.
|
||||
func (s *UserService) Delete(id, actorUserID uint) error {
|
||||
if id == 0 {
|
||||
return errors.New("用户不存在")
|
||||
}
|
||||
return nil
|
||||
if id == actorUserID {
|
||||
return errors.New("不能删除当前登录账号")
|
||||
}
|
||||
return s.db.Transaction(func(tx *gorm.DB) error {
|
||||
var user model.User
|
||||
if err := tx.First(&user, id).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return errors.New("用户不存在")
|
||||
}
|
||||
return err
|
||||
}
|
||||
if user.Role == model.RoleAdmin && user.Status == 1 {
|
||||
var admins int64
|
||||
if err := tx.Model(&model.User{}).Where("role = ? AND status = ?", model.RoleAdmin, 1).Count(&admins).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if admins <= 1 {
|
||||
return errors.New("至少保留一个启用的平台管理员")
|
||||
}
|
||||
}
|
||||
if err := tx.Where("user_id = ?", id).Delete(&model.MerchantMember{}).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Delete(&user).Error
|
||||
})
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user