go-wxhelper/internal/initialize/adminuser.go
2024-01-19 12:06:30 +08:00

73 lines
1.8 KiB
Go

package initialize
import (
"errors"
"gitee.ltd/lxh/logger/log"
"gorm.io/gorm"
"wechat-robot/internal/database"
"wechat-robot/model/entity"
"wechat-robot/utils"
)
// initDefaultAdminUser
// @description: 初始化默认后台用户
func initDefaultAdminUser() {
// 如果数据库没有有效用户,初始化一个默认账号
var count int64
if err := database.Client.Model(entity.AdminUser{}).Count(&count).Error; err != nil {
log.Panicf("初始化默认账号失败: %s", err.Error())
}
if count > 0 {
return
}
// 开启事务
var err error
tx := database.Client.Begin()
defer func() {
if recover() != nil {
tx.Rollback()
} else {
if err != nil {
tx.Rollback()
} else {
tx.Commit()
}
}
}()
// 判断角色是否存在
var role entity.Role
if err = tx.Where("code = ?", "admin").First(&role).Error; err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
log.Panicf("初始化默认账号失败: %s", err.Error())
return
}
// 如果角色不存在,创建角色
if role.Id == "" {
role.Name = "超级管理员"
role.Code = "admin"
role.Describe = "系统默认超级管理员"
if err = tx.Create(&role).Error; err != nil {
log.Panicf("初始化默认账号失败: %s", err.Error())
return
}
}
// 创建用户
var adminUser entity.AdminUser
adminUser.Username = "admin"
adminUser.Password = "admin123"
utils.PasswordUtils().HashPassword(&adminUser.Password)
if err = tx.Create(&adminUser).Error; err != nil {
log.Panicf("初始化默认账号失败: %s", err.Error())
return
}
// 绑定角色
var userRole entity.AdminUserRole
userRole.RoleId = role.Id
userRole.UserId = adminUser.Id
if err = tx.Create(&userRole).Error; err != nil {
log.Panicf("初始化默认账号失败: %s", err.Error())
return
}
}