77 lines
1.4 KiB
Go
77 lines
1.4 KiB
Go
package script
|
|
|
|
import (
|
|
"go.uber.org/zap"
|
|
"wireguard-dashboard/client"
|
|
"wireguard-dashboard/constant"
|
|
"wireguard-dashboard/model/entity"
|
|
"wireguard-dashboard/utils"
|
|
)
|
|
|
|
type Script struct{}
|
|
|
|
func NewScript() Script {
|
|
return Script{}
|
|
}
|
|
|
|
func (s Script) Do() error {
|
|
if err := s.DBMigrate(); err != nil {
|
|
return err
|
|
}
|
|
|
|
if err := s.CreateSuperAdmin(); err != nil {
|
|
return err
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
// DBMigrate
|
|
// @description: 实体migrate
|
|
// @receiver s
|
|
// @return error
|
|
func (s Script) DBMigrate() error {
|
|
var ent = []any{
|
|
new(entity.User),
|
|
new(entity.Server),
|
|
new(entity.Client),
|
|
}
|
|
|
|
return client.DB.AutoMigrate(ent...)
|
|
}
|
|
|
|
// CreateSuperAdmin
|
|
// @description: 创建首个超级管理员
|
|
// @receiver s
|
|
// @return error
|
|
func (s Script) CreateSuperAdmin() error {
|
|
var count int64
|
|
if err := client.DB.Model(&entity.User{}).Where("is_admin = ?", 1).Count(&count).Error; err != nil {
|
|
return err
|
|
}
|
|
|
|
// 没有超管就创建一个
|
|
if count <= 0 {
|
|
avatarPath, err := utils.Avatar().GenerateAvatar()
|
|
if err != nil {
|
|
zap.S().Errorf("生成头像失败: %v", err.Error())
|
|
return err
|
|
}
|
|
|
|
if err = client.DB.Create(&entity.User{
|
|
Avatar: avatarPath,
|
|
Name: "超牛管理员",
|
|
Account: "Admin",
|
|
Email: "",
|
|
Password: utils.Password().GenerateHashPassword("admin123"),
|
|
IsAdmin: constant.SuperAdmin,
|
|
}).Error; err != nil {
|
|
zap.S().Errorf("创建管理员失败: %v", err.Error())
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
return nil
|
|
}
|