66 lines
1.9 KiB
Go
66 lines
1.9 KiB
Go
package initdb
|
|
|
|
import (
|
|
"errors"
|
|
"os"
|
|
|
|
"git.apinb.com/heqiapp/platforms/backend/api/internal/impl"
|
|
"git.apinb.com/heqiapp/platforms/backend/api/internal/logic/common"
|
|
"git.apinb.com/heqiapp/platforms/backend/api/internal/models"
|
|
"golang.org/x/crypto/bcrypt"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
const (
|
|
PlatformRootUsername = "root"
|
|
PlatformRootPassword = "Heqi@Root2026"
|
|
PlatformRootRoleCode = "root"
|
|
)
|
|
|
|
// InitPlatformAccess 幂等初始化平台根角色;菜单定义位于逻辑层静态数据中。
|
|
func InitPlatformAccess() error {
|
|
rootRole := models.PlatformRole{
|
|
Entity: models.Entity{Identity: models.NewIdentity(), Status: common.StatusEnable},
|
|
RoleCode: PlatformRootRoleCode,
|
|
Name: "系统管理员",
|
|
LocationScope: "precise",
|
|
IsSystem: true,
|
|
}
|
|
return impl.DBService.Where("role_code = ?", rootRole.RoleCode).FirstOrCreate(&rootRole).Error
|
|
}
|
|
|
|
// InitPlatformRoot 幂等创建平台总后台 root 账户。
|
|
func InitPlatformRoot() error {
|
|
var account models.PlatformAccount
|
|
err := impl.DBService.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
|
|
}
|
|
|
|
account = models.PlatformAccount{
|
|
Entity: models.Entity{Identity: models.NewIdentity(), Status: common.StatusEnable},
|
|
Username: PlatformRootUsername,
|
|
DisplayName: "平台根管理员",
|
|
PasswordHash: string(passwordHash),
|
|
PlatformRoleCode: PlatformRootRoleCode,
|
|
Phone: "",
|
|
}
|
|
return impl.DBService.Create(&account).Error
|
|
}
|
|
|
|
// platformRootPassword 优先读取部署环境传入的 root 初始密码。
|
|
func platformRootPassword() string {
|
|
if password := os.Getenv("HEQI_PLATFORM_ROOT_PASSWORD"); common.IsValidAccountPassword(password) {
|
|
return password
|
|
}
|
|
return PlatformRootPassword
|
|
}
|