1
0
forked from baron/baron-sso

Merge commit '4696d7ce8228ebf46600a2c3bae27c3a8de01dda' into featur/tenantsign

This commit is contained in:
2026-02-19 17:09:22 +09:00
27 changed files with 534 additions and 734 deletions

View File

@@ -136,9 +136,6 @@ func main() {
}
slog.Info("✅ IDP Schema Validation Passed", "idp", idpProvider.Name())
// -----------------------------------
if err := bootstrap.SeedAdminIdentity(idpProvider); err != nil {
slog.Error("❌ Admin identity seed failed", "error", err)
}
// 2. Initialize DB Connections
// ClickHouse
@@ -212,6 +209,16 @@ func main() {
slog.Error("❌ Bootstrap failed", "error", err)
}
// [Moved & Enhanced] Seed Admin Identity & Sync Local Role
if kratosID, err := bootstrap.SeedAdminIdentity(idpProvider); err != nil {
slog.Error("❌ Admin identity seed failed", "error", err)
} else {
// Sync role to local DB
if err := bootstrap.SyncAdminRole(db, kratosID); err != nil {
slog.Error("❌ Admin role sync failed", "error", err)
}
}
// [New] Sync existing data to Keto
if ketoService != nil {
if err := bootstrap.SyncKetoRelations(db, ketoService); err != nil {

View File

@@ -5,19 +5,21 @@ import (
"log/slog"
"os"
"strings"
"time"
)
// SeedAdminIdentity creates the initial admin identity in the configured IDP.
func SeedAdminIdentity(idp domain.IdentityProvider) error {
// Returns the Kratos Identity ID and error.
func SeedAdminIdentity(idp domain.IdentityProvider) (string, error) {
if idp == nil {
return nil
return "", nil
}
adminEmail := strings.TrimSpace(os.Getenv("ADMIN_EMAIL"))
adminPassword := os.Getenv("ADMIN_PASSWORD")
if adminEmail == "" || adminPassword == "" {
slog.Warn("[Bootstrap] ADMIN_EMAIL or ADMIN_PASSWORD not set. Skipping admin identity seed.")
return nil
return "", nil
}
adminName := strings.TrimSpace(os.Getenv("ADMIN_NAME"))
@@ -34,18 +36,41 @@ func SeedAdminIdentity(idp domain.IdentityProvider) error {
"affiliationType": "internal",
"companyCode": "",
"grade": "admin",
"role": "super_admin", // Explicitly set role for Kratos traits
},
}
_, err := idp.CreateUser(user, adminPassword)
if err != nil {
if strings.Contains(err.Error(), "already exists") {
slog.Info("[Bootstrap] Admin identity already exists in IDP", "email", adminEmail)
return nil
// Retry logic for Kratos connection
maxRetries := 5
var err error
var identityID string
for i := 0; i < maxRetries; i++ {
identityID, err = idp.CreateUser(user, adminPassword)
if err == nil {
slog.Info("[Bootstrap] Admin identity created in IDP", "email", adminEmail, "idp", idp.Name(), "id", identityID)
return identityID, nil
}
return err
if strings.Contains(err.Error(), "already exists") {
slog.Info("[Bootstrap] Admin identity already exists in IDP. Attempting to retrieve ID...", "email", adminEmail)
// Try to sign in to get the identity ID
authInfo, err := idp.SignIn(adminEmail, adminPassword)
if err == nil && authInfo != nil {
slog.Info("[Bootstrap] Retrieved existing admin identity ID", "id", authInfo.Subject)
return authInfo.Subject, nil
}
slog.Warn("[Bootstrap] Failed to retrieve existing admin identity ID via SignIn", "error", err)
return "", nil // Return nil error to avoid stopping bootstrap, but ID is missing
}
slog.Warn("[Bootstrap] Failed to seed admin identity (retrying...)",
"attempt", i+1,
"max_retries", maxRetries,
"error", err,
)
time.Sleep(2 * time.Second)
}
slog.Info("[Bootstrap] Admin identity created in IDP", "email", adminEmail, "idp", idp.Name())
return nil
return "", err
}

View File

@@ -0,0 +1,77 @@
package bootstrap
import (
"baron-sso-backend/internal/domain"
"log/slog"
"os"
"strings"
"time"
"gorm.io/gorm"
)
// SyncAdminRole updates the role of the admin user in the local DB.
// It ensures the admin user exists in the local DB with the correct Kratos ID.
func SyncAdminRole(db *gorm.DB, kratosID string) error {
adminEmail := strings.TrimSpace(os.Getenv("ADMIN_EMAIL"))
if adminEmail == "" {
slog.Warn("[Bootstrap] ADMIN_EMAIL not set. Skipping admin role sync.")
return nil
}
adminName := strings.TrimSpace(os.Getenv("ADMIN_NAME"))
if adminName == "" {
adminName = "System Admin"
}
// Find user by email
var user domain.User
if err := db.Where("email = ?", adminEmail).First(&user).Error; err != nil {
if err == gorm.ErrRecordNotFound {
if kratosID == "" {
slog.Warn("[Bootstrap] Admin user not found in local DB and Kratos ID is missing. Cannot create local user.", "email", adminEmail)
return nil
}
// Create new admin user in local DB
newUser := domain.User{
ID: kratosID,
Email: adminEmail,
Name: adminName,
Role: domain.RoleSuperAdmin,
Status: "active",
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
Metadata: domain.JSONMap{"source": "bootstrap_seed"},
}
if err := db.Create(&newUser).Error; err != nil {
return err
}
slog.Info("[Bootstrap] Created admin user in local DB", "email", adminEmail, "id", kratosID)
return nil
}
return err
}
// Update role if needed
updates := map[string]interface{}{}
if user.Role != domain.RoleSuperAdmin {
updates["role"] = domain.RoleSuperAdmin
}
// Also ensure ID matches if it was somehow different (though changing PK is hard, at least log it)
if kratosID != "" && user.ID != kratosID {
slog.Warn("[Bootstrap] Admin user exists but ID mismatch with Kratos", "local_id", user.ID, "kratos_id", kratosID)
// We generally don't change UUID PKs, just warn.
}
if len(updates) > 0 {
if err := db.Model(&user).Updates(updates).Error; err != nil {
return err
}
slog.Info("[Bootstrap] Updated admin user role to super_admin", "email", adminEmail)
} else {
slog.Info("[Bootstrap] Admin user already has super_admin role", "email", adminEmail)
}
return nil
}

View File

@@ -1629,6 +1629,8 @@ func (h *AuthHandler) PasswordLogin(c *fiber.Ctx) error {
logOidcRedirectSummary("password_login", acceptResp.RedirectTo)
return c.JSON(fiber.Map{
"redirectTo": acceptResp.RedirectTo,
"status": "ok",
"provider": h.IdpProvider.Name(),
})
}
// --- OIDC 로그인 흐름 처리 끝 ---