fix mock seed root account reuse

This commit is contained in:
david
2026-07-29 16:12:46 +08:00
parent 969d7271f9
commit e2d5d29556

View File

@@ -2,6 +2,7 @@
package seed package seed
import ( import (
"errors"
"fmt" "fmt"
"reflect" "reflect"
"time" "time"
@@ -437,36 +438,40 @@ func MockData(database *gorm.DB) error {
return err return err
} }
role := models.PlatformRole{ return ensureMockRoot(tx, string(passwordHash))
Entity: entity(45, common.StatusEnable), RoleCode: "mock_operator",
Name: "模拟运营人员", LocationScope: "standard", IsSystem: false,
}
if err := put(tx, &role); err != nil {
return err
}
platformAccount := models.PlatformAccount{
Entity: entity(46, common.StatusEnable), Username: "mock_operator",
DisplayName: "模拟运营人员", PasswordHash: string(passwordHash),
PlatformRoleCode: role.RoleCode, Phone: "13600000001",
}
if err := put(tx, &platformAccount); err != nil {
return err
}
roleMenu := models.PlatformRoleMenu{
PlatformRoleID: role.ID, MenuIdentity: "dashboard_overview",
}
if err := tx.Where(
"platform_role_id = ? AND menu_identity = ?",
role.ID, roleMenu.MenuIdentity,
).FirstOrCreate(&roleMenu).Error; err != nil {
return fmt.Errorf("seed platform_role_menu: %w", err)
}
return nil
}) })
} }
// ensureMockRoot 复用已有 root 账号,仅在账号不存在时写入默认 root 用户。
func ensureMockRoot(database *gorm.DB, passwordHash string) error {
role := models.PlatformRole{
Entity: entity(45, common.StatusEnable), RoleCode: "root",
Name: "系统管理员", LocationScope: "precise", IsSystem: true,
}
if err := database.Where("role_code = ?", role.RoleCode).FirstOrCreate(&role).Error; err != nil {
return fmt.Errorf("seed root platform role: %w", err)
}
var account models.PlatformAccount
err := database.Where("username = ?", "root").First(&account).Error
if err == nil {
return nil
}
if !errors.Is(err, gorm.ErrRecordNotFound) {
return fmt.Errorf("find root platform account: %w", err)
}
account = models.PlatformAccount{
Entity: entity(46, common.StatusEnable), Username: "root",
DisplayName: "平台根管理员", PasswordHash: passwordHash,
PlatformRoleCode: role.RoleCode,
}
if err := database.Create(&account).Error; err != nil {
return fmt.Errorf("seed root platform account: %w", err)
}
return nil
}
func entity(sequence int, status int) models.Entity { func entity(sequence int, status int) models.Entity {
return models.Entity{ return models.Entity{
Identity: fmt.Sprintf("%s%012d", mockIdentityPrefix, sequence), Identity: fmt.Sprintf("%s%012d", mockIdentityPrefix, sequence),