forked from baron/baron-sso
73 lines
2.0 KiB
Go
73 lines
2.0 KiB
Go
package bootstrap
|
|
|
|
import (
|
|
"baron-sso-backend/internal/domain"
|
|
"baron-sso-backend/internal/repository"
|
|
"baron-sso-backend/internal/service"
|
|
"context"
|
|
"log/slog"
|
|
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
type InitialTenantConfig struct {
|
|
Name string
|
|
Slug string
|
|
Description string
|
|
Domains []string
|
|
}
|
|
|
|
// Hardcoded for now, can be moved to config file or env later
|
|
var defaultTenants = []InitialTenantConfig{
|
|
{
|
|
Name: "Hanmac Engineering",
|
|
Slug: "hanmac",
|
|
Description: "Primary Family Company",
|
|
Domains: []string{"hanmaceng.co.kr", "hmac.kr"},
|
|
},
|
|
}
|
|
|
|
func SeedTenants(db *gorm.DB) error {
|
|
slog.Info("[Bootstrap] Seeding initial tenants...")
|
|
repo := repository.NewTenantRepository(db)
|
|
userRepo := repository.NewUserRepository(db)
|
|
outboxRepo := repository.NewKetoOutboxRepository(db)
|
|
svc := service.NewTenantService(repo, userRepo, outboxRepo)
|
|
ctx := context.Background()
|
|
|
|
for _, config := range defaultTenants {
|
|
existing, err := repo.FindBySlug(ctx, config.Slug)
|
|
if err == nil && existing != nil {
|
|
slog.Info("[Bootstrap] Tenant already exists, checking domains...", "slug", config.Slug)
|
|
// Optional: Check and add missing domains
|
|
for _, d := range config.Domains {
|
|
found := false
|
|
for _, ed := range existing.Domains {
|
|
if ed.Domain == d {
|
|
found = true
|
|
break
|
|
}
|
|
}
|
|
if !found {
|
|
slog.Info("[Bootstrap] Adding missing domain to tenant", "slug", config.Slug, "domain", d)
|
|
if err := repo.AddDomain(ctx, existing.ID, d, true); err != nil {
|
|
slog.Error("Failed to add domain", "error", err)
|
|
}
|
|
}
|
|
}
|
|
continue
|
|
}
|
|
|
|
slog.Info("[Bootstrap] Creating default tenant", "name", config.Name, "slug", config.Slug)
|
|
tenant, err := svc.RegisterTenant(ctx, config.Name, config.Slug, domain.TenantTypeCompany, config.Description, config.Domains, nil)
|
|
if err != nil {
|
|
slog.Error("Failed to seed tenant", "slug", config.Slug, "error", err)
|
|
return err
|
|
}
|
|
// Explicitly set to active during seed
|
|
tenant.Status = domain.TenantStatusActive
|
|
db.Save(tenant)
|
|
}
|
|
return nil
|
|
}
|