bbs-backend/dal/init_db.go
2024-11-20 00:09:17 +08:00

118 lines
3.2 KiB
Go

// file name: init_db.go
package dal
import (
"bbs-backend/config"
"bbs-backend/dal/model"
"crypto/rand"
"encoding/base64"
"encoding/json"
"golang.org/x/crypto/argon2"
"log"
)
func MigrateAndSeedDB() {
// Load configuration
config.LoadConfig("config/config.yaml")
// Initialize the database
InitDB()
// Migrate the schema
err := DB.AutoMigrate(&model.User{}, &model.Post{}, &model.Comment{}, &model.Category{}, &model.Role{}, &model.Session{}, &model.BBSConfig{}, &model.Tag{})
if err != nil {
log.Fatalf("Failed to migrate database schema: %v", err)
}
// Seed initial roles
roles := []model.Role{
{Name: "admin"},
{Name: "editor"},
{Name: "viewer"},
}
for _, role := range roles {
if err := DB.FirstOrCreate(&role, model.Role{Name: role.Name}).Error; err != nil {
log.Fatalf("Failed to seed role: %v", err)
}
}
// Check if initial data already exists
var userCount int64
var categoryCount int64
var configCount int64
var tagCount int64
DB.Model(&model.User{}).Where("username = ?", "admin").Count(&userCount)
DB.Model(&model.Category{}).Where("name = ?", "General").Count(&categoryCount)
DB.Model(&model.BBSConfig{}).Count(&configCount)
DB.Model(&model.Tag{}).Where("name = ?", "default").Count(&tagCount)
if userCount == 0 {
// Seed initial user data
var adminRole model.Role
DB.Where("name = ?", "admin").First(&adminRole)
// Generate salt
salt := make([]byte, 16)
_, err := rand.Read(salt)
if err != nil {
log.Fatalf("Failed to generate salt: %v", err)
}
// Hash password using Argon2 id
hashedPassword := argon2.IDKey([]byte("admin123"), salt, 1, 64*1024, 4, 32)
// Set role IDs
roleIDs := []uint{adminRole.ID}
roleIDsJSON, _ := json.Marshal(roleIDs)
user := model.User{
Type: "admin",
Username: "admin",
Email: "admin@example.com",
Nickname: "Admin User",
AvatarURL: "",
Gender: "unknown",
HomePage: "",
Description: "This is the admin user.",
RoleIds: string(roleIDsJSON),
Status: "active",
Password: base64.StdEncoding.EncodeToString(hashedPassword),
Salt: base64.StdEncoding.EncodeToString(salt),
Roles: []model.Role{adminRole},
}
if err := DB.Create(&user).Error; err != nil {
log.Fatalf("Failed to seed user: %v", err)
}
}
if categoryCount == 0 {
// Seed initial category data
category := model.Category{Name: "General", Description: "General discussion"}
if err := DB.Create(&category).Error; err != nil {
log.Fatalf("Failed to seed category: %v", err)
}
}
if configCount == 0 {
// Seed initial config data
configs := []model.BBSConfig{
{Key: "forum_name", Value: "My BBS Forum"},
{Key: "forum_logo", Value: "https://example.com/logo.png"},
{Key: "forum_description", Value: "Welcome to our BBS forum!"},
}
for _, bbsConfig := range configs {
if err := DB.FirstOrCreate(&bbsConfig, model.BBSConfig{Key: bbsConfig.Key}).Error; err != nil {
log.Fatalf("Failed to seed BBS config: %v", err)
}
}
}
if tagCount == 0 {
// Seed initial tag data
tag := model.Tag{Name: "default"}
if err := DB.FirstOrCreate(&tag, model.Tag{Name: tag.Name}).Error; err != nil {
log.Fatalf("Failed to seed tag: %v", err)
}
}
}