wireguard-dashboard/script/db_migrate.go
2024-03-07 17:07:41 +08:00

148 lines
3.0 KiB
Go

package script
import (
"encoding/json"
"gitee.ltd/lxh/logger/log"
"golang.zx2c4.com/wireguard/wgctrl/wgtypes"
"wireguard-dashboard/client"
"wireguard-dashboard/constant"
"wireguard-dashboard/model/entity"
"wireguard-dashboard/repository"
"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
}
if err := s.InitServer(); err != nil {
log.Error(err.Error())
}
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),
new(entity.Setting),
}
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 {
return nil
}
// 生成一下头像
avatarPath, err := utils.Avatar().GenerateAvatar()
if err != nil {
log.Errorf("生成头像失败: %v", err.Error())
return err
}
if err = repository.User().Save(&entity.User{
Avatar: avatarPath,
Name: "超牛管理员",
Account: "Admin",
Email: "",
Password: utils.Password().GenerateHashPassword("admin123"),
IsAdmin: constant.SuperAdmin,
Status: constant.Normal,
}); err != nil {
return err
}
return nil
}
// InitServer
// @description: 初始化服务端信息
// @receiver s
// @return error
func (s Script) InitServer() error {
var count int64
if err := client.DB.Model(&entity.Server{}).Count(&count).Error; err != nil {
return err
}
if count > 0 {
return nil
}
// 初始化服务端的全局配置
var data = map[string]any{
"endpointAddress": utils.Network().GetHostPublicIP(),
"dnsServer": "10.10.10.1/24",
"MTU": 1450,
"persistentKeepalive": 15,
"firewallMark": "",
"table": "",
"configFilePath": "/etc/wireguard/wg0.conf",
}
dataJ, _ := json.Marshal(data)
globalSet := &entity.Setting{
Code: "SERVER_SETTING",
Data: string(dataJ),
Describe: "服务端全局配置",
}
if err := repository.System().Save(globalSet); err != nil {
return err
}
// 生成密钥
privateKey, err := wgtypes.GeneratePrivateKey()
if err != nil {
log.Errorf("生成密钥失败: %v", err.Error())
return err
}
// 根据密钥生成公钥
publicKey := privateKey.PublicKey()
// 没有服务端,开始初始化
if err := repository.Server().Save(&entity.Server{
IpScope: "10.10.10.1/24",
ListenPort: 51820,
PrivateKey: privateKey.String(),
PublicKey: publicKey.String(),
PostUpScript: "",
PreDownScript: "",
PostDownScript: "",
}); err != nil {
return err
}
return nil
}