2026-07-26 18:47:52 +08:00
|
|
|
package initdb
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"errors"
|
|
|
|
|
"os"
|
|
|
|
|
|
2026-07-29 13:18:52 +08:00
|
|
|
"git.apinb.com/heqiapp/platforms/backend/api/internal/logic/common"
|
2026-07-26 18:47:52 +08:00
|
|
|
"git.apinb.com/heqiapp/platforms/backend/api/internal/models"
|
|
|
|
|
"golang.org/x/crypto/bcrypt"
|
|
|
|
|
"gorm.io/gorm"
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
const (
|
|
|
|
|
// PlatformRootUsername 是平台总后台的内置根账号名称。
|
|
|
|
|
PlatformRootUsername = "root"
|
|
|
|
|
// PlatformRootPassword 是仅用于首次启动的初始密码,首次登录后必须修改。
|
|
|
|
|
PlatformRootPassword = "Heqi@Root2026"
|
|
|
|
|
// PlatformRootRoleCode 表示根账号的平台角色。
|
2026-07-27 00:18:42 +08:00
|
|
|
PlatformRootRoleCode = "root"
|
2026-07-26 18:47:52 +08:00
|
|
|
)
|
|
|
|
|
|
2026-07-29 13:18:52 +08:00
|
|
|
// InitPlatformAccess 幂等初始化 root 角色;菜单定义位于逻辑层静态数据中。
|
2026-07-27 00:18:42 +08:00
|
|
|
func InitPlatformAccess(database *gorm.DB) error {
|
|
|
|
|
rootRole := models.PlatformRole{
|
2026-07-29 14:25:38 +08:00
|
|
|
Entity: models.Entity{Identity: models.NewIdentity(), Status: common.StatusEnable},
|
|
|
|
|
RoleCode: PlatformRootRoleCode,
|
|
|
|
|
Name: "系统管理员",
|
|
|
|
|
LocationScope: "precise",
|
|
|
|
|
IsSystem: true,
|
2026-07-27 00:18:42 +08:00
|
|
|
}
|
2026-07-29 13:18:52 +08:00
|
|
|
return database.Where("role_code = ?", rootRole.RoleCode).FirstOrCreate(&rootRole).Error
|
2026-07-27 00:18:42 +08:00
|
|
|
}
|
|
|
|
|
|
2026-07-26 18:47:52 +08:00
|
|
|
// InitPlatformRoot 幂等创建平台总后台 root 账号。
|
|
|
|
|
func InitPlatformRoot(database *gorm.DB) error {
|
2026-07-28 13:35:59 +08:00
|
|
|
var account models.PlatformAccount
|
2026-07-26 18:47:52 +08:00
|
|
|
err := database.Where("username = ?", PlatformRootUsername).First(&account).Error
|
|
|
|
|
if err == nil {
|
|
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
if !errors.Is(err, gorm.ErrRecordNotFound) {
|
|
|
|
|
return err
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
passwordHash, err := bcrypt.GenerateFromPassword([]byte(platformRootPassword()), bcrypt.DefaultCost)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return err
|
|
|
|
|
}
|
|
|
|
|
|
2026-07-28 13:35:59 +08:00
|
|
|
account = models.PlatformAccount{
|
2026-07-29 13:18:52 +08:00
|
|
|
Entity: models.Entity{Identity: models.NewIdentity(), Status: common.StatusEnable},
|
2026-07-27 00:18:42 +08:00
|
|
|
Username: PlatformRootUsername,
|
|
|
|
|
DisplayName: "平台根管理员",
|
|
|
|
|
PasswordHash: string(passwordHash),
|
|
|
|
|
PlatformRoleCode: PlatformRootRoleCode,
|
|
|
|
|
Phone: "",
|
2026-07-26 18:47:52 +08:00
|
|
|
}
|
|
|
|
|
return database.Create(&account).Error
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// platformRootPassword 优先读取部署环境传入的 root 初始密码。
|
|
|
|
|
func platformRootPassword() string {
|
2026-07-30 10:01:19 +08:00
|
|
|
if password := os.Getenv("HEQI_PLATFORM_ROOT_PASSWORD"); common.IsValidAccountPassword(password) {
|
2026-07-26 18:47:52 +08:00
|
|
|
return password
|
|
|
|
|
}
|
|
|
|
|
return PlatformRootPassword
|
|
|
|
|
}
|