package service import ( "baron-sso-backend/internal/domain" "baron-sso-backend/internal/repository" "baron-sso-backend/internal/utils" "context" "errors" "log/slog" "strings" "gorm.io/gorm" ) type TenantService interface { RegisterTenant(ctx context.Context, name, slug, description string, domains []string, parentID *string) (*domain.Tenant, error) RequestRegistration(ctx context.Context, name, slug, description string, domainName string, adminEmail string) (*domain.Tenant, error) GetTenantByDomain(ctx context.Context, emailDomain string) (*domain.Tenant, error) GetTenantBySlug(ctx context.Context, slug string) (*domain.Tenant, error) GetTenant(ctx context.Context, id string) (*domain.Tenant, error) ApproveTenant(ctx context.Context, id string) error SetKetoService(keto KetoService) // 추가 } type tenantService struct { repo repository.TenantRepository userRepo repository.UserRepository keto KetoService outboxRepo repository.KetoOutboxRepository } func NewTenantService(repo repository.TenantRepository, userRepo repository.UserRepository, outboxRepo repository.KetoOutboxRepository) TenantService { return &tenantService{ repo: repo, userRepo: userRepo, outboxRepo: outboxRepo, } } func (s *tenantService) SetKetoService(keto KetoService) { s.keto = keto } func (s *tenantService) GetTenant(ctx context.Context, id string) (*domain.Tenant, error) { return s.repo.FindByID(ctx, id) } func (s *tenantService) ListManageableTenants(ctx context.Context, userID string) ([]domain.Tenant, error) { if s.keto == nil { return nil, errors.New("keto service not initialized") } // 1. 직접 관리자인 테넌트 ID 목록 (Tenant:ID#admins@User:ID) directAdminIDs, err := s.keto.ListObjects(ctx, "Tenant", "admins", "User:"+userID) if err != nil { slog.Error("Failed to list direct admin tenants", "userID", userID, "error", err) } // 2. 직접 소유자(조직장)인 테넌트 ID 목록 (Tenant:ID#owners@User:ID) directOwnerIDs, err := s.keto.ListObjects(ctx, "Tenant", "owners", "User:"+userID) if err != nil { slog.Error("Failed to list owned tenants", "userID", userID, "error", err) } // 합산 및 중복 제거 allIDsMap := make(map[string]bool) for _, id := range directAdminIDs { allIDsMap[id] = true } for _, id := range directOwnerIDs { allIDsMap[id] = true } // Note: 상속된 권한(부모의 어드민이 자식의 어드민)은 Keto의 OPL에서 처리되므로, // 특정 유저가 'view' 또는 'manage' 권한을 가진 테넌트를 모두 찾으려면 // Keto의 'expand' 또는 'list objects' 기능을 더 고도화하거나, // 여기서는 직접 할당된 부모 테넌트를 기준으로 하위 테넌트 정보를 추가 조회하는 로직이 필요할 수 있습니다. // 우선 직접 할당된 테넌트들만 반환합니다. allIDs := make([]string, 0, len(allIDsMap)) for id := range allIDsMap { allIDs = append(allIDs, id) } if len(allIDs) == 0 { return []domain.Tenant{}, nil } return s.repo.FindByIDs(ctx, allIDs) } func (s *tenantService) RegisterTenant(ctx context.Context, name, slug, description string, domains []string, parentID *string) (*domain.Tenant, error) { // Validate Slug if ok, msg := utils.ValidateSlug(slug); !ok { return nil, errors.New(msg) } // 1. Check if slug exists existing, err := s.repo.FindBySlug(ctx, slug) if err == nil && existing != nil { return nil, errors.New("tenant slug already exists") } if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) { return nil, err } // 2. Create Tenant tenant := &domain.Tenant{ Type: domain.TenantTypeCompany, // Default to COMPANY for manual registration Name: name, Slug: slug, Description: description, Status: domain.TenantStatusActive, ParentID: parentID, } if err := s.repo.Create(ctx, tenant); err != nil { return nil, err } // [Keto] Sync hierarchy via Outbox if ParentID exists if s.outboxRepo != nil && tenant.ParentID != nil { _ = s.outboxRepo.Create(ctx, &domain.KetoOutbox{ Namespace: "Tenant", Object: tenant.ID, Relation: "parents", Subject: "Tenant:" + *tenant.ParentID, Action: domain.KetoOutboxActionCreate, }) } // 3. Add Domains (Auto-verify for manual admin registration) for _, d := range domains { if err := s.repo.AddDomain(ctx, tenant.ID, d, true); err != nil { slog.Error("Failed to add domain to tenant", "tenant", slug, "domain", d, "error", err) } } return s.repo.FindBySlug(ctx, slug) } func (s *tenantService) RequestRegistration(ctx context.Context, name, slug, description string, domainName string, adminEmail string) (*domain.Tenant, error) { // Validate Slug if ok, msg := utils.ValidateSlug(slug); !ok { return nil, errors.New(msg) } // Verify that adminEmail domain matches the requested domainName parts := strings.Split(adminEmail, "@") if len(parts) != 2 || parts[1] != domainName { return nil, errors.New("admin email domain must match the tenant domain") } tenant := &domain.Tenant{ Type: domain.TenantTypeCompany, Name: name, Slug: slug, Description: description, Status: domain.TenantStatusPending, Config: domain.JSONMap{"adminEmail": adminEmail}, } if err := s.repo.Create(ctx, tenant); err != nil { return nil, err } // Add Domain as unverified if err := s.repo.AddDomain(ctx, tenant.ID, domainName, false); err != nil { return nil, err } return tenant, nil } func (s *tenantService) ApproveTenant(ctx context.Context, id string) error { tenant, err := s.repo.FindByID(ctx, id) if err != nil { return err } tenant.Status = domain.TenantStatusActive if err := s.repo.Update(ctx, tenant); err != nil { return err } // [Keto] Sync relation via Outbox if s.outboxRepo != nil { if adminEmail, ok := tenant.Config["adminEmail"].(string); ok && adminEmail != "" { slog.Info("Queueing tenant admin sync to Keto", "tenant", tenant.Slug, "adminEmail", adminEmail) // Check if user already exists in our Read-Model if s.userRepo != nil { user, err := s.userRepo.FindByEmail(ctx, adminEmail) if err == nil && user != nil { // User exists, assign Admin role in Keto via Outbox _ = s.outboxRepo.Create(ctx, &domain.KetoOutbox{ Namespace: "Tenant", Object: tenant.ID, Relation: "admins", Subject: "User:" + user.ID, Action: domain.KetoOutboxActionCreate, }) } else { slog.Info("Tenant admin user not found in local DB, will need manual sync or sync on signup", "email", adminEmail) } } } } return nil } func (s *tenantService) GetTenantByDomain(ctx context.Context, emailDomain string) (*domain.Tenant, error) { tenant, err := s.repo.FindByDomain(ctx, emailDomain) if err != nil { return nil, err } // Only return ACTIVE tenants for auto-assignment if tenant.Status != domain.TenantStatusActive { return nil, errors.New("tenant is not active") } return tenant, nil } func (s *tenantService) GetTenantBySlug(ctx context.Context, slug string) (*domain.Tenant, error) { return s.repo.FindBySlug(ctx, slug) }