49 lines
1.4 KiB
Go
49 lines
1.4 KiB
Go
|
|
package model
|
|||
|
|
|
|||
|
|
import (
|
|||
|
|
"fmt"
|
|||
|
|
"gorm.io/gorm"
|
|||
|
|
"math/rand"
|
|||
|
|
"time"
|
|||
|
|
)
|
|||
|
|
|
|||
|
|
// 定义随机字符集
|
|||
|
|
const passwordChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
|
|||
|
|
|
|||
|
|
// Yggdrasil ygg密码与用户id绑定
|
|||
|
|
type Yggdrasil struct {
|
|||
|
|
ID int64 `gorm:"column:id;primaryKey;not null" json:"id"`
|
|||
|
|
Password string `gorm:"column:password;not null" json:"password"`
|
|||
|
|
// 关联 - Yggdrasil的ID引用User的ID,但不自动创建外键约束(避免循环依赖)
|
|||
|
|
User *User `gorm:"foreignKey:ID;references:ID;constraint:OnDelete:CASCADE,OnUpdate:CASCADE" json:"user,omitempty"`
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
func (Yggdrasil) TableName() string { return "Yggdrasil" }
|
|||
|
|
|
|||
|
|
// AfterCreate User创建后自动同步生成GeneratePassword记录
|
|||
|
|
func (u *User) AfterCreate(tx *gorm.DB) error {
|
|||
|
|
randomPwd := GenerateRandomPassword(16)
|
|||
|
|
|
|||
|
|
// 创建GeneratePassword记录
|
|||
|
|
gp := Yggdrasil{
|
|||
|
|
ID: u.ID, // 关联User的ID
|
|||
|
|
Password: randomPwd, // 16位随机密码
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
if err := tx.Create(&gp).Error; err != nil {
|
|||
|
|
// 若同步失败,可记录日志或回滚事务(根据业务需求处理)
|
|||
|
|
return fmt.Errorf("同步生成密码失败: %w", err)
|
|||
|
|
}
|
|||
|
|
return nil
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// GenerateRandomPassword 生成指定长度的随机字符串
|
|||
|
|
func GenerateRandomPassword(length int) string {
|
|||
|
|
rand.Seed(time.Now().UnixNano()) // 初始化随机数种子
|
|||
|
|
b := make([]byte, length)
|
|||
|
|
for i := range b {
|
|||
|
|
b[i] = passwordChars[rand.Intn(len(passwordChars))]
|
|||
|
|
}
|
|||
|
|
return string(b)
|
|||
|
|
}
|