fix(core,admin_basic,board,ecommerce,page,gdpr,verification): 설정 미러·자동 정리·탈퇴 원자성·일괄 선택 범위 정비
공개이슈 ··· 및 그 전수 해소분. - 설정 저장·복원·초기화가 상주 프로세스 미러를 갱신하도록 단일 소유자화 - 만료 데이터 자동 정리 예약 12종 신설, 파기는 기본키 배치로 분할 - 회원 탈퇴를 전 경로 원자화하고 관리자 상태변경 경로를 정식 탈퇴로 통일 - 일괄 처리 목록의 선택을 화면에 보이는 행으로 한정(selectionScope) - 비밀번호 정책 문구를 도메인 중립 라벨로 정정 - 정적 검사 2종·검증 스킬 설계 정합성 축 신설
This commit is contained in:
1 parent
49c155509e
commit
4e1ec6e001
136 files changed
+7016
-504
No files matched your search
@@ -0,0 +1,39 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Services\IdentityLogService;
|
||||
use Illuminate\Console\Command;
|
||||
|
||||
/**
|
||||
* 만료 시각이 지난 본인인증 challenge 를 만료 상태로 전환하는 커맨드
|
||||
*
|
||||
* 상태 전환만 수행하며 행을 삭제하지 않습니다 (물리 파기는 identity:prune-logs 담당).
|
||||
*/
|
||||
class ExpireIdentityChallengesCommand extends Command
|
||||
{
|
||||
/**
|
||||
* The name and signature of the console command.
|
||||
*/
|
||||
protected $signature = 'identity:expire-challenges';
|
||||
|
||||
/**
|
||||
* The console command description.
|
||||
*/
|
||||
protected $description = '만료 시각이 지난 본인인증 challenge 를 만료 처리합니다';
|
||||
|
||||
/**
|
||||
* Execute the console command.
|
||||
*
|
||||
* @param IdentityLogService $service 본인인증 이력 서비스
|
||||
* @return int 명령 실행 결과 코드
|
||||
*/
|
||||
public function handle(IdentityLogService $service): int
|
||||
{
|
||||
$expired = $service->expirePastDue();
|
||||
|
||||
$this->info("본인인증 challenge {$expired}건이 만료 처리되었습니다.");
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Services\ActivityLogService;
|
||||
use Illuminate\Console\Command;
|
||||
|
||||
/**
|
||||
* 보존 기간이 지난 활동 로그를 정리하는 커맨드
|
||||
*/
|
||||
class PruneActivityLogsCommand extends Command
|
||||
{
|
||||
/**
|
||||
* The name and signature of the console command.
|
||||
*/
|
||||
protected $signature = 'activity-log:prune {--days=365 : 보존 기간(일)}';
|
||||
|
||||
/**
|
||||
* The console command description.
|
||||
*/
|
||||
protected $description = '보존 기간이 지난 활동 로그를 삭제합니다';
|
||||
|
||||
/**
|
||||
* Execute the console command.
|
||||
*
|
||||
* 파기 자체는 도메인 서비스가 수행합니다 — 커맨드는 옵션만 전달합니다.
|
||||
* 보존 기간 하한과 확장 훅 발행은 그 계층이 소유합니다.
|
||||
*
|
||||
* @param ActivityLogService $service 활동 로그 서비스
|
||||
* @return int 명령 실행 결과 코드
|
||||
*/
|
||||
public function handle(ActivityLogService $service): int
|
||||
{
|
||||
$days = (int) $this->option('days');
|
||||
$deleted = $service->prune($days);
|
||||
|
||||
$this->info("활동 로그 {$deleted}건이 삭제되었습니다. (보존 {$days}일)");
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Services\IdentityLogService;
|
||||
use Illuminate\Console\Command;
|
||||
|
||||
/**
|
||||
* 보존 기간이 지난 본인인증 이력을 파기하는 커맨드
|
||||
*
|
||||
* 관리자 화면의 수동 파기 버튼과 동일한 기본 보관주기(180일)를 사용합니다.
|
||||
*/
|
||||
class PruneIdentityLogsCommand extends Command
|
||||
{
|
||||
/**
|
||||
* The name and signature of the console command.
|
||||
*/
|
||||
protected $signature = 'identity:prune-logs {--days=180 : 보관 기간(일)}';
|
||||
|
||||
/**
|
||||
* The console command description.
|
||||
*/
|
||||
protected $description = '보관 기간이 지난 본인인증 이력을 파기합니다';
|
||||
|
||||
/**
|
||||
* Execute the console command.
|
||||
*
|
||||
* 파기 자체는 도메인 서비스가 수행합니다 — 커맨드는 옵션만 전달하고,
|
||||
* 보존 기간 하한은 그 계층이 소유합니다.
|
||||
*
|
||||
* @param IdentityLogService $service 본인인증 이력 서비스
|
||||
* @return int 명령 실행 결과 코드
|
||||
*/
|
||||
public function handle(IdentityLogService $service): int
|
||||
{
|
||||
$days = (int) $this->option('days');
|
||||
$purged = $service->purge($days);
|
||||
|
||||
$this->info("본인인증 이력 {$purged}건이 파기되었습니다. (보관 {$days}일)");
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Services\NotificationLogService;
|
||||
use Illuminate\Console\Command;
|
||||
|
||||
/**
|
||||
* 보존 기간이 지난 알림 발송 이력을 정리하는 커맨드
|
||||
*/
|
||||
class PruneNotificationLogsCommand extends Command
|
||||
{
|
||||
/**
|
||||
* The name and signature of the console command.
|
||||
*/
|
||||
protected $signature = 'notification-log:prune {--days=90 : 보존 기간(일)}';
|
||||
|
||||
/**
|
||||
* The console command description.
|
||||
*/
|
||||
protected $description = '보존 기간이 지난 알림 발송 이력을 삭제합니다';
|
||||
|
||||
/**
|
||||
* Execute the console command.
|
||||
*
|
||||
* 파기 자체는 도메인 서비스가 수행합니다 — 커맨드는 옵션만 전달합니다.
|
||||
* 보존 기간 하한과 확장 훅 발행은 그 계층이 소유합니다.
|
||||
*
|
||||
* @param NotificationLogService $service 알림 발송 이력 서비스
|
||||
* @return int 명령 실행 결과 코드
|
||||
*/
|
||||
public function handle(NotificationLogService $service): int
|
||||
{
|
||||
$days = (int) $this->option('days');
|
||||
$deleted = $service->prune($days);
|
||||
|
||||
$this->info("알림 발송 이력 {$deleted}건이 삭제되었습니다. (보존 {$days}일)");
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Services\ScheduleService;
|
||||
use Illuminate\Console\Command;
|
||||
|
||||
/**
|
||||
* 보존 기간이 지난 스케줄 실행 이력을 정리하는 커맨드
|
||||
*
|
||||
* 이력 행은 출력(longText)을 포함해 실행마다 누적되므로 정리 주체가 없으면 무한히 성장합니다.
|
||||
*/
|
||||
class PruneScheduleHistoryCommand extends Command
|
||||
{
|
||||
/**
|
||||
* The name and signature of the console command.
|
||||
*/
|
||||
protected $signature = 'schedules:prune-history {--days=90 : 보존 기간(일)}';
|
||||
|
||||
/**
|
||||
* The console command description.
|
||||
*/
|
||||
protected $description = '보존 기간이 지난 스케줄 실행 이력을 삭제합니다';
|
||||
|
||||
/**
|
||||
* Execute the console command.
|
||||
*
|
||||
* 파기 자체는 도메인 서비스가 수행합니다 — 커맨드는 옵션만 전달합니다.
|
||||
* 보존 기간 하한과 확장 훅 발행은 그 계층이 소유합니다.
|
||||
*
|
||||
* @param ScheduleService $service 스케줄 서비스
|
||||
* @return int 명령 실행 결과 코드
|
||||
*/
|
||||
public function handle(ScheduleService $service): int
|
||||
{
|
||||
$days = (int) $this->option('days');
|
||||
$deleted = $service->pruneHistory($days);
|
||||
|
||||
$this->info("스케줄 실행 이력 {$deleted}건이 삭제되었습니다. (보존 {$days}일)");
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Seo\SeoCacheStatsService;
|
||||
use Illuminate\Console\Command;
|
||||
|
||||
/**
|
||||
* 보존 기간이 지난 SEO 캐시 통계를 정리하는 커맨드
|
||||
*
|
||||
* 통계 행은 봇 요청마다 누적되므로 정리 주체가 없으면 무한히 성장합니다.
|
||||
*/
|
||||
class PruneSeoCacheStatsCommand extends Command
|
||||
{
|
||||
/**
|
||||
* The name and signature of the console command.
|
||||
*/
|
||||
protected $signature = 'seo:prune-stats {--days=30 : 보존 기간(일)}';
|
||||
|
||||
/**
|
||||
* The console command description.
|
||||
*/
|
||||
protected $description = '보존 기간이 지난 SEO 캐시 통계 기록을 삭제합니다';
|
||||
|
||||
/**
|
||||
* Execute the console command.
|
||||
*
|
||||
* 파기 자체는 도메인 서비스가 수행합니다 — 커맨드는 옵션만 전달하고,
|
||||
* 보존 기간 하한은 그 계층이 소유합니다.
|
||||
*
|
||||
* @param SeoCacheStatsService $service SEO 캐시 통계 서비스
|
||||
* @return int 명령 실행 결과 코드
|
||||
*/
|
||||
public function handle(SeoCacheStatsService $service): int
|
||||
{
|
||||
$days = (int) $this->option('days');
|
||||
$deleted = $service->cleanup($days);
|
||||
|
||||
$this->info("SEO 캐시 통계 {$deleted}건이 삭제되었습니다. (보존 {$days}일)");
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -65,4 +65,12 @@ interface ActivityLogRepositoryInterface
|
||||
* @return int 익명화된 row 수
|
||||
*/
|
||||
public function anonymizeUserId(int $userId): int;
|
||||
|
||||
/**
|
||||
* 보존 기간이 지난 활동 로그를 삭제합니다.
|
||||
*
|
||||
* @param int $days 보존 기간 (일)
|
||||
* @return int 삭제된 건수
|
||||
*/
|
||||
public function deleteOlderThan(int $days): int;
|
||||
}
|
||||
@@ -40,6 +40,14 @@ interface NotificationLogRepositoryInterface
|
||||
*/
|
||||
public function bulkDelete(array $ids): int;
|
||||
|
||||
/**
|
||||
* 보존 기간이 지난 발송 이력을 삭제합니다.
|
||||
*
|
||||
* @param int $days 보존 기간 (일)
|
||||
* @return int 삭제된 건수
|
||||
*/
|
||||
public function deleteOlderThan(int $days): int;
|
||||
|
||||
/**
|
||||
* 페이지네이션 목록 조회.
|
||||
*
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
<?php
|
||||
|
||||
use App\Support\ExtensionSettingsMirror;
|
||||
use Illuminate\Support\Facades\Config;
|
||||
|
||||
if (! function_exists('g7_settings')) {
|
||||
@@ -16,15 +17,12 @@ if (! function_exists('g7_settings')) {
|
||||
* @example
|
||||
* // 코어 메일 설정 조회
|
||||
* $mailHost = g7_settings('core.mail.host');
|
||||
*
|
||||
* @example
|
||||
* // 모듈 설정 조회
|
||||
* $shopName = g7_settings('modules.sirsoft-ecommerce.basic_info.shop_name');
|
||||
*
|
||||
* @example
|
||||
* // 플러그인 설정 조회
|
||||
* $displayMode = g7_settings('plugins.sirsoft-daum_postcode.display_mode');
|
||||
*
|
||||
* @example
|
||||
* // 전체 설정 조회
|
||||
* $allSettings = g7_settings();
|
||||
@@ -50,7 +48,6 @@ if (! function_exists('g7_core_settings')) {
|
||||
* @example
|
||||
* // 메일 호스트 조회
|
||||
* $mailHost = g7_core_settings('mail.host');
|
||||
*
|
||||
* @example
|
||||
* // 사이트명 조회
|
||||
* $siteName = g7_core_settings('general.site_name');
|
||||
@@ -77,7 +74,6 @@ if (! function_exists('g7_module_settings')) {
|
||||
* @example
|
||||
* // 이커머스 모듈의 쇼핑몰명 조회
|
||||
* $shopName = g7_module_settings('sirsoft-ecommerce', 'basic_info.shop_name');
|
||||
*
|
||||
* @example
|
||||
* // 모듈 전체 설정 조회
|
||||
* $allSettings = g7_module_settings('sirsoft-ecommerce');
|
||||
@@ -92,6 +88,23 @@ if (! function_exists('g7_module_settings')) {
|
||||
}
|
||||
}
|
||||
|
||||
if (! function_exists('g7_refresh_module_settings_config')) {
|
||||
/**
|
||||
* 모듈 환경설정 config 미러를 다시 채웁니다.
|
||||
*
|
||||
* 모듈 설정 저장에는 코어 공통 지점이 없어 각 모듈의 SettingsService 가 직접 저장합니다.
|
||||
* 그 서비스가 자기 캐시를 비우는 자리에서 이 헬퍼를 호출하면, 상주 프로세스에서도
|
||||
* `g7_module_settings()` 가 저장 직후의 값을 읽습니다 (공개이슈 #109).
|
||||
*
|
||||
* @param string $identifier 모듈 식별자 (예: sirsoft-ecommerce)
|
||||
* @return void
|
||||
*/
|
||||
function g7_refresh_module_settings_config(string $identifier): void
|
||||
{
|
||||
app(ExtensionSettingsMirror::class)->refreshModule($identifier);
|
||||
}
|
||||
}
|
||||
|
||||
if (! function_exists('g7_plugin_settings')) {
|
||||
/**
|
||||
* 그누보드7 플러그인 환경설정 조회 헬퍼 함수
|
||||
@@ -104,7 +117,6 @@ if (! function_exists('g7_plugin_settings')) {
|
||||
* @example
|
||||
* // 다음 우편번호 플러그인의 표시 모드 조회
|
||||
* $displayMode = g7_plugin_settings('sirsoft-daum_postcode', 'display_mode');
|
||||
*
|
||||
* @example
|
||||
* // 플러그인 전체 설정 조회
|
||||
* $allSettings = g7_plugin_settings('sirsoft-daum_postcode');
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
namespace App\Http\Controllers\Api\Auth;
|
||||
|
||||
use App\Enums\AttachmentSourceType;
|
||||
use App\Exceptions\CannotDeleteSuperAdminException;
|
||||
use App\Http\Controllers\Api\Base\AuthBaseController;
|
||||
use App\Http\Requests\Auth\VerifyPasswordRequest;
|
||||
use App\Http\Requests\User\ChangePasswordRequest;
|
||||
@@ -302,12 +303,23 @@ class ProfileController extends AuthBaseController
|
||||
return $this->unauthorized('auth.unauthenticated');
|
||||
}
|
||||
|
||||
$this->logUserActivity('profile.withdraw');
|
||||
|
||||
// 사용자 탈퇴 처리 (아바타, 토큰 삭제 및 익명화)
|
||||
$this->userService->withdrawUser($user);
|
||||
|
||||
// 활동 로그는 성공한 뒤에만 남긴다 — 실패한 탈퇴가 기록으로 남으면
|
||||
// 이력만 보고는 탈퇴한 것으로 읽힌다.
|
||||
$this->logUserActivity('profile.withdraw');
|
||||
|
||||
return $this->success('user.withdraw_success');
|
||||
} catch (ValidationException $e) {
|
||||
// 관리자/수퍼관리자 탈퇴 차단은 요청이 잘못된 것이지 서버 오류가 아니다.
|
||||
return $this->validationError($e->errors(), 'user.withdraw_failed');
|
||||
} catch (CannotDeleteSuperAdminException $e) {
|
||||
// 이 예외는 ValidationException 을 상속하지 않으므로 별도 매핑이 필요하다.
|
||||
return $this->validationError(
|
||||
['general' => [$e->getMessage()]],
|
||||
'user.withdraw_failed'
|
||||
);
|
||||
} catch (\Exception $e) {
|
||||
return $this->error('user.withdraw_failed', 500, null, ['error' => $e->getMessage()]);
|
||||
}
|
||||
|
||||
@@ -880,25 +880,25 @@ class SaveSettingsRequest extends FormRequest
|
||||
'general.site_description' => __('validation.attributes.site_description'),
|
||||
'general.admin_email' => __('validation.attributes.admin_email'),
|
||||
'general.timezone' => __('validation.attributes.timezone'),
|
||||
'general.language' => __('validation.attributes.language'),
|
||||
'general.language' => __('validation.attributes.default_language'),
|
||||
// 본인인증(IDV) 필드
|
||||
'identity.default_provider' => __('validation.attributes.identity_default_provider'),
|
||||
'identity.purpose_providers' => __('validation.attributes.identity_purpose_providers'),
|
||||
'identity.challenge_ttl_minutes' => __('validation.attributes.identity_challenge_ttl_minutes'),
|
||||
'identity.max_attempts' => __('validation.attributes.identity_max_attempts'),
|
||||
// notifications
|
||||
'notifications.channels' => __('validation.attributes.channels'),
|
||||
'notifications.channels' => __('validation.attributes.notification_channels'),
|
||||
// general
|
||||
'general.currency' => __('validation.attributes.currency'),
|
||||
'general.currency' => __('validation.attributes.default_currency'),
|
||||
'general.maintenance_mode' => __('validation.attributes.maintenance_mode'),
|
||||
'general.asset_url_mode' => __('validation.attributes.asset_url_mode'),
|
||||
'general.site_logo' => __('validation.attributes.site_logo'),
|
||||
// mail
|
||||
'mail.mailer' => __('validation.attributes.mailer'),
|
||||
'mail.host' => __('validation.attributes.host'),
|
||||
'mail.port' => __('validation.attributes.port'),
|
||||
'mail.username' => __('validation.attributes.username'),
|
||||
'mail.password' => __('validation.attributes.password'),
|
||||
'mail.host' => __('validation.attributes.smtp_host'),
|
||||
'mail.port' => __('validation.attributes.smtp_port'),
|
||||
'mail.username' => __('validation.attributes.smtp_username'),
|
||||
'mail.password' => __('validation.attributes.smtp_password'),
|
||||
'mail.encryption' => __('validation.attributes.encryption'),
|
||||
'mail.mailgun_domain' => __('validation.attributes.mailgun_domain'),
|
||||
'mail.mailgun_secret' => __('validation.attributes.mailgun_secret'),
|
||||
@@ -930,7 +930,7 @@ class SaveSettingsRequest extends FormRequest
|
||||
'seo.twitter_default_card' => __('validation.attributes.twitter_default_card'),
|
||||
'seo.twitter_default_site' => __('validation.attributes.twitter_default_site'),
|
||||
'seo.cache_enabled' => __('validation.attributes.seo_page_cache_enabled'),
|
||||
'seo.cache_ttl' => __('validation.attributes.cache_ttl'),
|
||||
'seo.cache_ttl' => __('validation.attributes.seo_page_cache_ttl'),
|
||||
'seo.sitemap_enabled' => __('validation.attributes.sitemap_enabled'),
|
||||
'seo.sitemap_cache_ttl' => __('validation.attributes.sitemap_cache_ttl'),
|
||||
'seo.sitemap_urls_per_file' => __('validation.attributes.sitemap_urls_per_file'),
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
namespace App\Http\Requests\Settings;
|
||||
|
||||
use App\Extension\HookManager;
|
||||
use Illuminate\Contracts\Validation\ValidationRule;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
|
||||
/**
|
||||
@@ -25,7 +26,7 @@ class TestMailRequest extends FormRequest
|
||||
/**
|
||||
* 검증 규칙을 반환합니다.
|
||||
*
|
||||
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
|
||||
* @return array<string, ValidationRule|array<mixed>|string>
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
@@ -72,8 +73,8 @@ class TestMailRequest extends FormRequest
|
||||
'to_email.max' => __('settings.invalid_email'),
|
||||
'from_address.required' => __('validation.required', ['attribute' => __('validation.attributes.from_address')]),
|
||||
'from_name.required' => __('validation.required', ['attribute' => __('validation.attributes.from_name')]),
|
||||
'host.required' => __('validation.required', ['attribute' => __('validation.attributes.host')]),
|
||||
'port.required' => __('validation.required', ['attribute' => __('validation.attributes.port')]),
|
||||
'host.required' => __('validation.required', ['attribute' => __('validation.attributes.smtp_host')]),
|
||||
'port.required' => __('validation.required', ['attribute' => __('validation.attributes.smtp_port')]),
|
||||
'mailgun_domain.required' => __('validation.required', ['attribute' => __('validation.attributes.mailgun_domain')]),
|
||||
'mailgun_secret.required' => __('validation.required', ['attribute' => __('validation.attributes.mailgun_secret')]),
|
||||
'ses_key.required' => __('validation.required', ['attribute' => __('validation.attributes.ses_key')]),
|
||||
@@ -81,4 +82,22 @@ class TestMailRequest extends FormRequest
|
||||
'ses_region.required' => __('validation.required', ['attribute' => __('validation.attributes.ses_region')]),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 검증 속성명을 반환합니다.
|
||||
*
|
||||
* 범용 필드명(host/port/username/password)은 전역 라벨이 범용 문구이므로,
|
||||
* SMTP 전용 라벨을 이 요청에서만 명시 매핑합니다.
|
||||
*
|
||||
* @return array<string, string>
|
||||
*/
|
||||
public function attributes(): array
|
||||
{
|
||||
return [
|
||||
'host' => __('validation.attributes.smtp_host'),
|
||||
'port' => __('validation.attributes.smtp_port'),
|
||||
'username' => __('validation.attributes.smtp_username'),
|
||||
'password' => __('validation.attributes.smtp_password'),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ use App\Enums\UserStatus;
|
||||
use App\Extension\HookManager;
|
||||
use App\Models\User;
|
||||
use App\Rules\ExcludeCurrentUser;
|
||||
use Illuminate\Contracts\Validation\ValidationRule;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Validation\Rule;
|
||||
|
||||
@@ -13,17 +14,20 @@ class BulkUpdateUserStatusRequest extends FormRequest
|
||||
{
|
||||
/**
|
||||
* 요청 권한을 확인합니다.
|
||||
*
|
||||
* 권한 검사는 라우트의 `permission:admin,core.users.update` 미들웨어가 담당합니다.
|
||||
*
|
||||
* @return bool 항상 true (미들웨어에서 권한 제어)
|
||||
*/
|
||||
public function authorize(): bool
|
||||
{
|
||||
// 사용자 업데이트 권한 확인
|
||||
return $this->user()->can('core.users.update');
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 검증 규칙을 정의합니다.
|
||||
*
|
||||
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
|
||||
* @return array<string, ValidationRule|array<mixed>|string>
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
@@ -45,9 +49,9 @@ class BulkUpdateUserStatusRequest extends FormRequest
|
||||
public function messages(): array
|
||||
{
|
||||
return [
|
||||
'ids.required' => __('validation.required', ['attribute' => __('validation.attributes.ids')]),
|
||||
'ids.array' => __('validation.array', ['attribute' => __('validation.attributes.ids')]),
|
||||
'ids.min' => __('validation.min.array', ['attribute' => __('validation.attributes.ids'), 'min' => 1]),
|
||||
'ids.required' => __('validation.required', ['attribute' => __('validation.attributes.user_ids')]),
|
||||
'ids.array' => __('validation.array', ['attribute' => __('validation.attributes.user_ids')]),
|
||||
'ids.min' => __('validation.min.array', ['attribute' => __('validation.attributes.user_ids'), 'min' => 1]),
|
||||
'ids.*.required' => __('validation.required', ['attribute' => __('validation.attributes.user_id')]),
|
||||
'ids.*.uuid' => __('validation.uuid', ['attribute' => __('validation.attributes.user_id')]),
|
||||
'ids.*.exists' => __('validation.exists', ['attribute' => __('validation.attributes.user_id')]),
|
||||
@@ -55,4 +59,20 @@ class BulkUpdateUserStatusRequest extends FormRequest
|
||||
'status.in' => __('validation.in', ['attribute' => __('validation.attributes.status')]),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 검증 속성명을 반환합니다.
|
||||
*
|
||||
* 범용 필드명 ids 는 전역 라벨이 범용 문구이므로,
|
||||
* 사용자 대상 라벨을 이 요청에서만 명시 매핑합니다.
|
||||
*
|
||||
* @return array<string, string>
|
||||
*/
|
||||
public function attributes(): array
|
||||
{
|
||||
return [
|
||||
'ids' => __('validation.attributes.user_ids'),
|
||||
'ids.*' => __('validation.attributes.user_id'),
|
||||
];
|
||||
}
|
||||
}
|
||||
+10
-1
@@ -7,6 +7,7 @@ use App\Enums\ScheduleFrequency;
|
||||
use App\Enums\ScheduleResultStatus;
|
||||
use App\Enums\ScheduleType;
|
||||
use App\Models\Concerns\HasUserOverrides;
|
||||
use Carbon\Carbon;
|
||||
use Cron\CronExpression;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
@@ -153,8 +154,16 @@ class Schedule extends Model
|
||||
}
|
||||
|
||||
try {
|
||||
// cron 식은 사이트 설정 시간대로 해석한다 — 코드 예약(app.schedule_timezone)과
|
||||
// 같은 기준이어야 같은 화면에서 "새벽 4시" 의 근거가 어긋나지 않는다.
|
||||
// 계산 결과는 저장 타임존(app.timezone = UTC)으로 되돌려 저장한다.
|
||||
$storeTimezone = (string) config('app.timezone', 'UTC');
|
||||
$scheduleTimezone = (string) config('app.schedule_timezone', $storeTimezone);
|
||||
|
||||
$cron = new CronExpression($this->expression);
|
||||
$this->next_run_at = $cron->getNextRunDate();
|
||||
$nextRun = $cron->getNextRunDate('now', 0, false, $scheduleTimezone);
|
||||
|
||||
$this->next_run_at = Carbon::instance($nextRun)->setTimezone($storeTimezone);
|
||||
} catch (\Exception $e) {
|
||||
$this->next_run_at = null;
|
||||
}
|
||||
|
||||
+50
-3
@@ -15,6 +15,7 @@ use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
use Illuminate\Database\Eloquent\Relations\MorphOne;
|
||||
use Illuminate\Database\Schema\Builder as SchemaBuilder;
|
||||
use Illuminate\Foundation\Auth\User as Authenticatable;
|
||||
use Illuminate\Notifications\Notifiable;
|
||||
use Laravel\Sanctum\HasApiTokens;
|
||||
@@ -24,6 +25,11 @@ class User extends Authenticatable implements HasLocalePreference
|
||||
/** @use HasFactory<UserFactory> */
|
||||
use HasApiTokens, HasFactory, Notifiable;
|
||||
|
||||
/**
|
||||
* 닉네임 컬럼 최대 길이 (마이그레이션에서 명시한 값)
|
||||
*/
|
||||
public const NICKNAME_MAX_LENGTH = 50;
|
||||
|
||||
/** @var array<string, array> 활동 로그 추적 필드 */
|
||||
public static array $activityLogFields = [
|
||||
'name' => ['label_key' => 'activity_log.fields.name', 'type' => 'text'],
|
||||
@@ -602,20 +608,39 @@ class User extends Authenticatable implements HasLocalePreference
|
||||
*/
|
||||
public function withdraw(): bool
|
||||
{
|
||||
// 멱등 가드 — 이미 탈퇴한 계정에 다시 호출해도 접미사가 겹쳐 붙지 않는다.
|
||||
if ($this->isWithdrawn()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
$now = now();
|
||||
$dateSuffix = $now->format('Ymd'); // 예: 20260127
|
||||
|
||||
// name/email 은 마이그레이션에서 길이를 지정하지 않은 문자열 컬럼이므로
|
||||
// 스키마 기본 길이(AppServiceProvider 의 defaultStringLength)를 그대로 따른다.
|
||||
// 여기에 리터럴을 박으면 기본 길이를 바꾸는 순간 조용히 어긋난다.
|
||||
$defaultLength = SchemaBuilder::$defaultStringLength ?? 255;
|
||||
|
||||
// 이름에 suffix 추가 (있는 경우만)
|
||||
if ($this->name) {
|
||||
$this->name = $this->name.'_탈퇴_'.$dateSuffix;
|
||||
$this->name = $this->appendWithdrawnSuffix($this->name, '_탈퇴_'.$dateSuffix, $defaultLength);
|
||||
}
|
||||
|
||||
// 이메일에 suffix 추가 (필수)
|
||||
$this->email = $this->email.'_deleted_'.$dateSuffix;
|
||||
//
|
||||
// 접미사에 사용자 ID 를 포함해 구조적으로 유일하게 만든다. 날짜만 붙이면
|
||||
// 같은 이메일로 재가입한 회원이 같은 날 다시 탈퇴할 때 email unique 에
|
||||
// 걸려 탈퇴가 실패한다(공개이슈 #112).
|
||||
$this->email = $this->appendWithdrawnSuffix(
|
||||
$this->email,
|
||||
'_deleted_'.$dateSuffix.'_'.$this->id,
|
||||
$defaultLength,
|
||||
);
|
||||
|
||||
// 닉네임에 suffix 추가 (있는 경우만, 날짜 없이)
|
||||
if ($this->nickname) {
|
||||
$this->nickname = $this->nickname.'_탈퇴';
|
||||
// nickname 은 마이그레이션에서 길이를 명시(50)한 컬럼이다.
|
||||
$this->nickname = $this->appendWithdrawnSuffix($this->nickname, '_탈퇴', self::NICKNAME_MAX_LENGTH);
|
||||
}
|
||||
|
||||
// 상태 변경
|
||||
@@ -624,4 +649,26 @@ class User extends Authenticatable implements HasLocalePreference
|
||||
|
||||
return $this->save();
|
||||
}
|
||||
|
||||
/**
|
||||
* 탈퇴 접미사를 컬럼 길이 안에서 부착합니다.
|
||||
*
|
||||
* 원값이 길면 접미사 길이만큼 앞을 잘라 붙입니다 — 자르지 않으면 접미사가 컬럼
|
||||
* 길이를 넘겨 strict mode 저장 예외가 나고, 탈퇴가 중간에서 실패합니다.
|
||||
*
|
||||
* @param string $value 원본 값
|
||||
* @param string $suffix 부착할 접미사
|
||||
* @param int $maxLength 컬럼 최대 길이
|
||||
* @return string 접미사가 부착된 값
|
||||
*/
|
||||
protected function appendWithdrawnSuffix(string $value, string $suffix, int $maxLength): string
|
||||
{
|
||||
$available = $maxLength - mb_strlen($suffix);
|
||||
|
||||
if ($available < 0) {
|
||||
$available = 0;
|
||||
}
|
||||
|
||||
return mb_substr($value, 0, $available).$suffix;
|
||||
}
|
||||
}
|
||||
@@ -10,7 +10,6 @@ use App\Console\Commands\BenchCommand;
|
||||
use App\Contracts\Extension\CacheInterface;
|
||||
use App\Contracts\Extension\ExtensionMiddlewareRegistryInterface;
|
||||
use App\Contracts\Extension\HookListenerInterface;
|
||||
use App\Contracts\Extension\ModuleSettingsInterface;
|
||||
use App\Contracts\Extension\StorageInterface;
|
||||
use App\Contracts\Extension\TemplateManagerInterface;
|
||||
use App\Contracts\Repositories\ActivityLogRepositoryInterface;
|
||||
@@ -97,6 +96,7 @@ use App\Services\DriverRegistryService;
|
||||
use App\Services\LayoutExtensionService;
|
||||
use App\Services\TemplateLayoutAttachmentService;
|
||||
use App\Services\UniqueIdService;
|
||||
use App\Support\ExtensionSettingsMirror;
|
||||
use App\Support\PrivilegedDatabaseAccounts;
|
||||
use Illuminate\Support\Facades\Config;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
@@ -739,69 +739,8 @@ class CoreServiceProvider extends ServiceProvider
|
||||
*/
|
||||
protected function loadModuleSettingsToConfig(ModuleManager $moduleManager): void
|
||||
{
|
||||
$moduleSettings = [];
|
||||
|
||||
foreach (array_keys($moduleManager->getActiveModules()) as $identifier) {
|
||||
try {
|
||||
// 모듈별 환경설정 서비스 조회
|
||||
$settingsService = $this->resolveModuleSettingsService($identifier);
|
||||
|
||||
if ($settingsService instanceof ModuleSettingsInterface) {
|
||||
$settings = $settingsService->getAllSettings();
|
||||
if (! empty($settings)) {
|
||||
$moduleSettings[$identifier] = $settings;
|
||||
}
|
||||
}
|
||||
} catch (\Throwable $e) {
|
||||
Log::warning("모듈 환경설정 로딩 실패: {$identifier}", [
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
Config::set('g7_settings.modules', $moduleSettings);
|
||||
}
|
||||
|
||||
/**
|
||||
* 모듈의 환경설정 서비스를 찾아 인스턴스화합니다.
|
||||
*
|
||||
* 다음 순서로 설정 서비스를 찾습니다:
|
||||
* 1. 인터페이스 바인딩: Modules\Vendor\Module\Contracts\ModuleSettingsServiceInterface
|
||||
* 2. 구체 클래스: Modules\Vendor\Module\Services\ModuleSettingsService
|
||||
*
|
||||
* @param string $identifier 모듈 식별자 (예: sirsoft-ecommerce)
|
||||
* @return ModuleSettingsInterface|null 설정 서비스 인스턴스
|
||||
*/
|
||||
protected function resolveModuleSettingsService(string $identifier): ?ModuleSettingsInterface
|
||||
{
|
||||
// vendor-module 형식을 네임스페이스로 변환
|
||||
$parts = explode('-', $identifier);
|
||||
if (count($parts) < 2) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$vendor = ucfirst($parts[0]);
|
||||
$moduleName = ucfirst($parts[1]);
|
||||
|
||||
// 1. 인터페이스 바인딩 확인
|
||||
$interfaceClass = "Modules\\{$vendor}\\{$moduleName}\\Contracts\\{$moduleName}SettingsServiceInterface";
|
||||
if ($this->app->bound($interfaceClass)) {
|
||||
$service = $this->app->make($interfaceClass);
|
||||
if ($service instanceof ModuleSettingsInterface) {
|
||||
return $service;
|
||||
}
|
||||
}
|
||||
|
||||
// 2. 구체 클래스 확인
|
||||
$concreteClass = "Modules\\{$vendor}\\{$moduleName}\\Services\\{$moduleName}SettingsService";
|
||||
if (class_exists($concreteClass)) {
|
||||
$service = $this->app->make($concreteClass);
|
||||
if ($service instanceof ModuleSettingsInterface) {
|
||||
return $service;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
// 미러 채움 로직은 ExtensionSettingsMirror 가 단일 소유한다 (공개이슈 #109).
|
||||
app(ExtensionSettingsMirror::class)->refreshAllModules();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -814,28 +753,9 @@ class CoreServiceProvider extends ServiceProvider
|
||||
*/
|
||||
protected function loadPluginSettingsToConfig(PluginManager $pluginManager): void
|
||||
{
|
||||
$pluginSettings = [];
|
||||
|
||||
foreach (array_keys($pluginManager->getActivePlugins()) as $identifier) {
|
||||
try {
|
||||
$settingsPath = storage_path("app/plugins/{$identifier}/settings/setting.json");
|
||||
|
||||
if (File::exists($settingsPath)) {
|
||||
$content = File::get($settingsPath);
|
||||
$settings = json_decode($content, true);
|
||||
|
||||
if (json_last_error() === JSON_ERROR_NONE && ! empty($settings)) {
|
||||
$pluginSettings[$identifier] = $settings;
|
||||
}
|
||||
}
|
||||
} catch (\Throwable $e) {
|
||||
Log::warning("플러그인 환경설정 로딩 실패: {$identifier}", [
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
Config::set('g7_settings.plugins', $pluginSettings);
|
||||
// 종전에는 setting.json 을 raw 로 읽어 defaults 병합·정규화가 빠지고 암호문이 그대로
|
||||
// 실렸다 — 값의 형태가 전용 게터와 달랐다. 이제 미러 소유자에 위임한다 (공개이슈 #109).
|
||||
app(ExtensionSettingsMirror::class)->refreshAllPlugins();
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -4,6 +4,7 @@ namespace App\Providers;
|
||||
|
||||
use App\Repositories\JsonConfigRepository;
|
||||
use App\Support\AllowedExtensions;
|
||||
use App\Support\ExtensionSettingsMirror;
|
||||
use Illuminate\Support\Facades\Config;
|
||||
use Illuminate\Support\ServiceProvider;
|
||||
use Predis\Client;
|
||||
@@ -16,23 +17,8 @@ use Predis\Client;
|
||||
*/
|
||||
class SettingsServiceProvider extends ServiceProvider
|
||||
{
|
||||
/**
|
||||
* 코어 설정 카테고리 목록
|
||||
*/
|
||||
private const CORE_CATEGORIES = [
|
||||
'mail',
|
||||
'general',
|
||||
'security',
|
||||
'debug',
|
||||
'drivers',
|
||||
'cache',
|
||||
'upload',
|
||||
'core_update',
|
||||
'geoip',
|
||||
'seo',
|
||||
'identity',
|
||||
'pagination',
|
||||
];
|
||||
// 코어 설정 카테고리 목록은 ExtensionSettingsMirror::CORE_CATEGORIES 가 단독 소유한다.
|
||||
// 여기에 사본을 두면 미러가 읽는 목록과 갈라져도 아무도 알아채지 못한다.
|
||||
|
||||
/**
|
||||
* 서비스를 등록합니다.
|
||||
@@ -41,6 +27,10 @@ class SettingsServiceProvider extends ServiceProvider
|
||||
*/
|
||||
public function register(): void
|
||||
{
|
||||
// 미러 채움 소유자를 컨테이너 싱글톤으로 등록한다 — 부팅/저장/테스트가
|
||||
// 같은 인스턴스를 해석해야 교체(스텁 주입)가 모든 경로에 통한다.
|
||||
$this->app->singleton(ExtensionSettingsMirror::class);
|
||||
|
||||
// JsonConfigRepository를 직접 인스턴스화 (DI 컨테이너 사용 불가)
|
||||
$configRepository = new JsonConfigRepository;
|
||||
|
||||
@@ -67,16 +57,9 @@ class SettingsServiceProvider extends ServiceProvider
|
||||
*/
|
||||
private function loadCoreSettingsToConfig(JsonConfigRepository $configRepository): void
|
||||
{
|
||||
$coreSettings = [];
|
||||
|
||||
foreach (self::CORE_CATEGORIES as $category) {
|
||||
$settings = $configRepository->getCategory($category);
|
||||
if (! empty($settings)) {
|
||||
$coreSettings[$category] = $settings;
|
||||
}
|
||||
}
|
||||
|
||||
Config::set('g7_settings.core', $coreSettings);
|
||||
// 미러 채움 로직은 ExtensionSettingsMirror 가 단일 소유한다 —
|
||||
// 저장 시점 재채움(공개이슈 #109)과 같은 코드를 써야 부팅과 저장의 결과가 갈리지 않는다.
|
||||
$this->app->make(ExtensionSettingsMirror::class)->refreshCore($configRepository);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -188,6 +171,14 @@ class SettingsServiceProvider extends ServiceProvider
|
||||
// 환경설정의 timezone은 사용자 표시용 기본 타임존
|
||||
// app.timezone(서버 저장 타임존)은 항상 UTC 유지
|
||||
Config::set('app.default_user_timezone', $generalSettings['timezone']);
|
||||
|
||||
// 예약 작업의 시각 해석 기준도 사이트 설정 시간대를 따른다.
|
||||
// Laravel 의 Kernel::scheduleTimezone() 이 이 키를 읽어 Schedule 인스턴스
|
||||
// 전체에 일괄 적용하므로, 코어·확장이 등록한 모든 예약이 같은 기준을 공유한다.
|
||||
// (이벤트마다 ->timezone() 을 붙이는 방식은 나중에 추가되는 예약이
|
||||
// 조용히 UTC 기준으로 돌아가므로 채택하지 않는다.)
|
||||
// 미설정 시에는 Laravel 기본 폴백(app.timezone = UTC)이 그대로 적용된다.
|
||||
Config::set('app.schedule_timezone', $generalSettings['timezone']);
|
||||
}
|
||||
|
||||
if (! empty($generalSettings['language'])) {
|
||||
|
||||
@@ -7,6 +7,7 @@ use App\Helpers\PermissionHelper;
|
||||
use App\Helpers\TimezoneHelper;
|
||||
use App\Http\Resources\BaseApiCollection;
|
||||
use App\Models\ActivityLog;
|
||||
use App\Repositories\Concerns\DeletesInBatches;
|
||||
use App\Repositories\Concerns\HasMultipleSearchFilters;
|
||||
use App\Repositories\Concerns\PaginatesWithDeferredJoin;
|
||||
use App\Repositories\Concerns\ResolvesSortSpec;
|
||||
@@ -23,6 +24,7 @@ use Illuminate\Database\Eloquent\Model;
|
||||
*/
|
||||
class ActivityLogRepository implements ActivityLogRepositoryInterface
|
||||
{
|
||||
use DeletesInBatches;
|
||||
use HasMultipleSearchFilters;
|
||||
use PaginatesWithDeferredJoin;
|
||||
use ResolvesSortSpec;
|
||||
@@ -316,4 +318,20 @@ class ActivityLogRepository implements ActivityLogRepositoryInterface
|
||||
{
|
||||
return ActivityLog::where('user_id', $userId)->update(['user_id' => null]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 보존 기간이 지난 활동 로그를 삭제합니다.
|
||||
*
|
||||
* 보존 기간 하한(1일)은 이 계층이 소유한다 — 파기는 되돌릴 수 없으므로 호출자마다
|
||||
* 다시 막지 않고 실제로 지우는 자리에서 한 번 막는다.
|
||||
*
|
||||
* @param int $days 보존 기간 (일)
|
||||
* @return int 삭제된 건수
|
||||
*/
|
||||
public function deleteOlderThan(int $days): int
|
||||
{
|
||||
return $this->deleteInBatches(
|
||||
ActivityLog::where('created_at', '<', now()->subDays(max(1, $days)))
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
<?php
|
||||
|
||||
namespace App\Repositories\Concerns;
|
||||
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
|
||||
/**
|
||||
* 보존 기간 초과 행을 배치로 나눠 삭제하는 트레이트
|
||||
*
|
||||
* 정리 예약은 도입 직후 첫 실행에서 이미 쌓여 있던 과거 데이터를 전부 지운다.
|
||||
* 수년치가 한 문장으로 삭제되면 그 한 건이 테이블을 오래 잠그고, 트랜잭션 로그도
|
||||
* 그만큼 부풀어 정리 배치가 사이트를 멈추게 한다 — 정리하려던 문제를 정리 작업이
|
||||
* 다시 만드는 셈이다.
|
||||
*
|
||||
* 그래서 기본키 배치로 끊어 지운다. 각 DELETE 는 최대 batchSize 건의 기본키 IN 절이라
|
||||
* 잠금 구간이 짧고, 중간에 중단돼도 이미 지운 만큼은 확정된다(정리는 멱등이라
|
||||
* 다음 실행이 남은 몫을 이어서 처리한다).
|
||||
*/
|
||||
trait DeletesInBatches
|
||||
{
|
||||
/**
|
||||
* 기본 배치 크기
|
||||
*/
|
||||
protected int $deleteBatchSize = 1000;
|
||||
|
||||
/**
|
||||
* 조건에 맞는 행을 배치로 나눠 삭제합니다.
|
||||
*
|
||||
* 기본키를 먼저 모아 그 키로만 지운다 — `DELETE ... LIMIT` 은 드라이버마다 지원이
|
||||
* 갈리지만 기본키 IN 절은 어디서나 같게 동작한다.
|
||||
*
|
||||
* @param Builder $query 삭제 대상 조건이 적용된 쿼리 (정렬·제한 미적용 상태)
|
||||
* @param int|null $batchSize 배치 크기 (미지정 시 $deleteBatchSize)
|
||||
* @return int 삭제된 총 건수
|
||||
*/
|
||||
protected function deleteInBatches(Builder $query, ?int $batchSize = null): int
|
||||
{
|
||||
$batchSize = max(1, $batchSize ?? $this->deleteBatchSize);
|
||||
$model = $query->getModel();
|
||||
$keyName = $model->getKeyName();
|
||||
$total = 0;
|
||||
|
||||
while (true) {
|
||||
// audit:allow query-repeated-execution 배치 삭제는 같은 술어를 의도적으로 반복 평가한다 — 매 회차의 모집단이 직전 삭제로 줄어든다
|
||||
$keys = (clone $query)->orderBy($keyName)->limit($batchSize)->pluck($keyName);
|
||||
|
||||
if ($keys->isEmpty()) {
|
||||
return $total;
|
||||
}
|
||||
|
||||
$total += $model->newQuery()->whereIn($keyName, $keys)->delete();
|
||||
|
||||
// 마지막 배치 — 더 조회할 것이 없다
|
||||
if ($keys->count() < $batchSize) {
|
||||
return $total;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,7 @@ use App\Enums\IdentityVerificationStatus;
|
||||
use App\Helpers\TimezoneHelper;
|
||||
use App\Models\IdentityPolicy;
|
||||
use App\Models\IdentityVerificationLog;
|
||||
use App\Repositories\Concerns\DeletesInBatches;
|
||||
use App\Repositories\Concerns\PaginatesWithDeferredJoin;
|
||||
use App\Support\Query\PaginationLimits;
|
||||
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
|
||||
@@ -19,6 +20,7 @@ use Illuminate\Support\Carbon;
|
||||
*/
|
||||
class IdentityVerificationLogRepository implements IdentityVerificationLogRepositoryInterface
|
||||
{
|
||||
use DeletesInBatches;
|
||||
use PaginatesWithDeferredJoin;
|
||||
|
||||
/**
|
||||
@@ -127,9 +129,10 @@ class IdentityVerificationLogRepository implements IdentityVerificationLogReposi
|
||||
*/
|
||||
public function purgeOlderThan(int $days): int
|
||||
{
|
||||
return IdentityVerificationLog::query()
|
||||
->where('created_at', '<', Carbon::now()->subDays(max(1, $days)))
|
||||
->delete();
|
||||
return $this->deleteInBatches(
|
||||
IdentityVerificationLog::query()
|
||||
->where('created_at', '<', Carbon::now()->subDays(max(1, $days)))
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -6,6 +6,7 @@ use App\Contracts\Repositories\NotificationLogRepositoryInterface;
|
||||
use App\Enums\NotificationLogStatus;
|
||||
use App\Models\NotificationLog;
|
||||
use App\Models\User;
|
||||
use App\Repositories\Concerns\DeletesInBatches;
|
||||
use App\Repositories\Concerns\PaginatesWithDeferredJoin;
|
||||
use App\Repositories\Concerns\ResolvesSortSpec;
|
||||
use App\Support\Query\KeysetPaginator;
|
||||
@@ -17,6 +18,7 @@ use Illuminate\Pagination\LengthAwarePaginator;
|
||||
|
||||
class NotificationLogRepository implements NotificationLogRepositoryInterface
|
||||
{
|
||||
use DeletesInBatches;
|
||||
use PaginatesWithDeferredJoin;
|
||||
use ResolvesSortSpec;
|
||||
|
||||
@@ -98,6 +100,22 @@ class NotificationLogRepository implements NotificationLogRepositoryInterface
|
||||
return NotificationLog::whereIn('id', $ids)->delete();
|
||||
}
|
||||
|
||||
/**
|
||||
* 보존 기간이 지난 발송 이력을 삭제합니다.
|
||||
*
|
||||
* 보존 기간 하한(1일)은 이 계층이 소유한다 — 파기는 되돌릴 수 없으므로 호출자마다
|
||||
* 다시 막지 않고 실제로 지우는 자리에서 한 번 막는다.
|
||||
*
|
||||
* @param int $days 보존 기간 (일)
|
||||
* @return int 삭제된 건수
|
||||
*/
|
||||
public function deleteOlderThan(int $days): int
|
||||
{
|
||||
return $this->deleteInBatches(
|
||||
NotificationLog::where('created_at', '<', now()->subDays(max(1, $days)))
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 페이지네이션 목록 조회.
|
||||
*
|
||||
|
||||
@@ -4,6 +4,7 @@ namespace App\Repositories;
|
||||
|
||||
use App\Contracts\Repositories\ScheduleHistoryRepositoryInterface;
|
||||
use App\Models\ScheduleHistory;
|
||||
use App\Repositories\Concerns\DeletesInBatches;
|
||||
use App\Repositories\Concerns\PaginatesWithDeferredJoin;
|
||||
use App\Repositories\Concerns\ResolvesSortSpec;
|
||||
use App\Support\Query\PaginationLimits;
|
||||
@@ -13,6 +14,7 @@ use Illuminate\Database\Eloquent\Collection;
|
||||
|
||||
class ScheduleHistoryRepository implements ScheduleHistoryRepositoryInterface
|
||||
{
|
||||
use DeletesInBatches;
|
||||
use PaginatesWithDeferredJoin;
|
||||
use ResolvesSortSpec;
|
||||
|
||||
@@ -169,6 +171,10 @@ class ScheduleHistoryRepository implements ScheduleHistoryRepositoryInterface
|
||||
*/
|
||||
public function deleteOlderThan(int $days): int
|
||||
{
|
||||
return ScheduleHistory::where('started_at', '<', now()->subDays($days))->delete();
|
||||
// 보존 기간 하한(1일)은 이 계층이 소유한다 — 파기는 되돌릴 수 없으므로
|
||||
// 호출자마다 다시 막지 않고 실제로 지우는 자리에서 한 번 막는다.
|
||||
return $this->deleteInBatches(
|
||||
ScheduleHistory::where('started_at', '<', now()->subDays(max(1, $days)))
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ namespace App\Repositories;
|
||||
|
||||
use App\Contracts\Repositories\SeoCacheStatRepositoryInterface;
|
||||
use App\Models\SeoCacheStat;
|
||||
use App\Repositories\Concerns\DeletesInBatches;
|
||||
use Carbon\Carbon;
|
||||
use Illuminate\Contracts\Database\Query\Expression;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
@@ -16,6 +17,8 @@ use Illuminate\Support\Facades\DB;
|
||||
*/
|
||||
class SeoCacheStatRepository implements SeoCacheStatRepositoryInterface
|
||||
{
|
||||
use DeletesInBatches;
|
||||
|
||||
/**
|
||||
* 그룹 집계에 허용된 컬럼 목록
|
||||
*
|
||||
@@ -96,7 +99,7 @@ class SeoCacheStatRepository implements SeoCacheStatRepositoryInterface
|
||||
*/
|
||||
public function deleteOlderThan(Carbon $cutoff): int
|
||||
{
|
||||
return SeoCacheStat::where('created_at', '<', $cutoff)->delete();
|
||||
return $this->deleteInBatches(SeoCacheStat::where('created_at', '<', $cutoff));
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -127,6 +127,10 @@ class SeoCacheStatsService
|
||||
*/
|
||||
public function cleanup(int $daysToKeep = 30): int
|
||||
{
|
||||
// 보존 기간 하한(1일)은 이 계층이 소유한다 — 파기는 되돌릴 수 없으므로
|
||||
// 호출자마다 다시 막지 않고 실제로 지우는 경로에서 한 번 막는다.
|
||||
$daysToKeep = max(1, $daysToKeep);
|
||||
|
||||
$deleted = $this->statRepository->deleteOlderThan(Carbon::now()->subDays($daysToKeep));
|
||||
|
||||
Log::info('[SEO] 캐시 통계 정리 완료', [
|
||||
|
||||
@@ -83,4 +83,26 @@ class ActivityLogService
|
||||
|
||||
return $count;
|
||||
}
|
||||
|
||||
/**
|
||||
* 보존 기간이 지난 활동 로그를 정리합니다 (자동 파기).
|
||||
*
|
||||
* 운영자가 고른 ID 를 지우는 deleteMany 와는 별개의 훅을 발행한다. 자동 파기는
|
||||
* 대상을 ID 로 지목하지 않고(기간으로 정한다), 사람이 없는 예약 실행이라
|
||||
* 본인인증 같은 대화형 가드를 태울 수 없기 때문이다. 확장은 이 훅으로
|
||||
* 외부 보관 등 자기 처리를 붙인다.
|
||||
*
|
||||
* @param int $days 보존 기간 (일)
|
||||
* @return int 삭제된 건수
|
||||
*/
|
||||
public function prune(int $days): int
|
||||
{
|
||||
HookManager::doAction('core.activity_log.before_prune', $days);
|
||||
|
||||
$count = $this->repository->deleteOlderThan($days);
|
||||
|
||||
HookManager::doAction('core.activity_log.after_prune', $days, $count);
|
||||
|
||||
return $count;
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,7 @@ use Illuminate\Auth\Access\AuthorizationException;
|
||||
use Illuminate\Http\UploadedFile;
|
||||
use Illuminate\Support\Collection;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\Support\Str;
|
||||
use Symfony\Component\HttpFoundation\StreamedResponse;
|
||||
@@ -181,23 +182,40 @@ class AttachmentService
|
||||
$attachmentableId = $attachment->attachmentable_id;
|
||||
$collection = $attachment->collection;
|
||||
|
||||
// Before 훅
|
||||
HookManager::doAction('core.attachment.before_delete', $attachment);
|
||||
// DB 를 먼저 지우고 파일은 커밋 후에 지운다.
|
||||
// 순서를 반대로 두면 DB 삭제가 실패했을 때 파일 없는 행이 남아 다운로드가 404 가 된다.
|
||||
// 반대로 이 순서에서는 최악이어도 참조되지 않는 고아 파일만 남고 데이터는 온전하다.
|
||||
$result = DB::transaction(function () use ($id, $attachment, $attachmentableType, $attachmentableId, $collection) {
|
||||
// Before 훅
|
||||
HookManager::doAction('core.attachment.before_delete', $attachment);
|
||||
|
||||
// 스토리지에서 파일 삭제
|
||||
$this->storage->withDisk($attachment->disk)->delete('', $attachment->path);
|
||||
// DB에서 영구 삭제
|
||||
$deleted = $this->repository->forceDelete($id);
|
||||
|
||||
// DB에서 영구 삭제
|
||||
$result = $this->repository->forceDelete($id);
|
||||
// 삭제 후 남은 파일들의 순서 재정렬
|
||||
if ($deleted && $attachmentableType && $attachmentableId) {
|
||||
$this->repository->reorderAfterDelete($attachmentableType, $attachmentableId, $collection);
|
||||
}
|
||||
|
||||
Log::info('첨부파일 삭제 완료', [
|
||||
'attachment_id' => $id,
|
||||
'hash' => $attachment->hash,
|
||||
]);
|
||||
return $deleted;
|
||||
});
|
||||
|
||||
// 삭제 후 남은 파일들의 순서 재정렬
|
||||
if ($result && $attachmentableType && $attachmentableId) {
|
||||
$this->repository->reorderAfterDelete($attachmentableType, $attachmentableId, $collection);
|
||||
if ($result) {
|
||||
// 커밋 후 스토리지 파일 삭제 (실패해도 DB 는 되돌리지 않는다)
|
||||
try {
|
||||
$this->storage->withDisk($attachment->disk)->delete('', $attachment->path);
|
||||
} catch (\Throwable $e) {
|
||||
Log::warning('첨부파일 스토리지 삭제 실패 (고아 파일 잔존)', [
|
||||
'attachment_id' => $id,
|
||||
'path' => $attachment->path,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
}
|
||||
|
||||
Log::info('첨부파일 삭제 완료', [
|
||||
'attachment_id' => $id,
|
||||
'hash' => $attachment->hash,
|
||||
]);
|
||||
}
|
||||
|
||||
// After 훅
|
||||
@@ -378,18 +396,29 @@ class AttachmentService
|
||||
// Before 훅
|
||||
HookManager::doAction('core.attachment.before_bulk_delete', $identifier);
|
||||
|
||||
// 해당 첨부파일들의 스토리지 파일 삭제
|
||||
// 삭제 대상 스냅샷 + 파일 경로를 먼저 수집한다 (DB 삭제 후에는 조회할 수 없다).
|
||||
$attachments = $this->repository->getBySourceIdentifier($identifier);
|
||||
$attachmentIds = $attachments->pluck('id')->toArray();
|
||||
$snapshots = $attachments->keyBy('id')->map(fn ($a) => $a->toArray())->toArray();
|
||||
$files = $attachments->map(fn ($a) => ['disk' => $a->disk, 'path' => $a->path])->all();
|
||||
|
||||
foreach ($attachments as $attachment) {
|
||||
$this->storage->withDisk($attachment->disk)->delete('', $attachment->path);
|
||||
// DB 일괄 삭제를 먼저 커밋한다 — 루프 중간에 실패하면 파일만 일부 사라지고
|
||||
// DB 행은 전부 남아 다운로드가 404 가 되기 때문이다.
|
||||
$count = DB::transaction(fn () => $this->repository->deleteBySourceIdentifier($identifier));
|
||||
|
||||
// 커밋 후 파일 정리 (실패해도 DB 는 되돌리지 않는다 — 고아 파일은 비파괴)
|
||||
foreach ($files as $file) {
|
||||
try {
|
||||
$this->storage->withDisk($file['disk'])->delete('', $file['path']);
|
||||
} catch (\Throwable $e) {
|
||||
Log::warning('첨부파일 스토리지 일괄 삭제 실패 (고아 파일 잔존)', [
|
||||
'source_identifier' => $identifier,
|
||||
'path' => $file['path'],
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
// DB에서 삭제
|
||||
$count = $this->repository->deleteBySourceIdentifier($identifier);
|
||||
|
||||
Log::info('소스 식별자 기준 첨부파일 일괄 삭제', [
|
||||
'source_identifier' => $identifier,
|
||||
'deleted_count' => $count,
|
||||
|
||||
@@ -15,6 +15,7 @@ use App\Extension\HookManager;
|
||||
use App\Models\User;
|
||||
use Carbon\Carbon;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\Support\Str;
|
||||
@@ -347,19 +348,27 @@ class AuthService
|
||||
'status' => $status,
|
||||
];
|
||||
|
||||
$user = $this->userRepository->create($userData);
|
||||
// 계정 생성 이후 단계에서 실패하면 이메일만 점유한 유령 계정이 남아
|
||||
// 같은 이메일로 재가입조차 불가능해진다. 생성~토큰 발급을 하나로 묶는다.
|
||||
[$user, $token] = DB::transaction(function () use ($userData, $data, $now) {
|
||||
$user = $this->userRepository->create($userData);
|
||||
|
||||
// 약관 동의 이력 기록
|
||||
$this->recordConsents($user, $data, $now);
|
||||
// 약관 동의 이력 기록
|
||||
$this->recordConsents($user, $data, $now);
|
||||
|
||||
// 'user' 역할 자동 할당 (UserService 패턴과 동일)
|
||||
$userRole = $this->roleRepository->findByIdentifier('user');
|
||||
if ($userRole) {
|
||||
$user->roles()->sync([$userRole->id]);
|
||||
$user->flushPermissionCaches();
|
||||
}
|
||||
// 'user' 역할 자동 할당 (UserService 패턴과 동일)
|
||||
$userRole = $this->roleRepository->findByIdentifier('user');
|
||||
if ($userRole) {
|
||||
$user->roles()->sync([$userRole->id]);
|
||||
}
|
||||
|
||||
$token = $user->createToken('auth-token', ['*'], $this->getTokenExpiresAt())->plainTextToken;
|
||||
$token = $user->createToken('auth-token', ['*'], $this->getTokenExpiresAt())->plainTextToken;
|
||||
|
||||
return [$user, $token];
|
||||
});
|
||||
|
||||
// 커밋 후 부수효과 (캐시는 DB 트랜잭션의 롤백 대상이 아니다)
|
||||
$user->flushPermissionCaches();
|
||||
|
||||
// Hook 발생 (회원가입 완료) — 알림 발송은 NotificationHookListener,
|
||||
// signup_after_create 정책이 enabled 면 InitiateIdentityChallengeAfterRegister 가 challenge 발행.
|
||||
@@ -612,16 +621,20 @@ class AuthService
|
||||
]);
|
||||
}
|
||||
|
||||
// Hook 발생 (비밀번호 재설정 시작)
|
||||
HookManager::doAction('core.auth.before_reset_password', $user);
|
||||
// 비밀번호를 바꾼 뒤 토큰 삭제가 실패하면 그 재설정 토큰이 계속 유효한 채로
|
||||
// 남아 재사용된다(보안). 두 단계를 하나로 묶는다.
|
||||
DB::transaction(function () use ($user, $password, $record) {
|
||||
// Hook 발생 (비밀번호 재설정 시작)
|
||||
HookManager::doAction('core.auth.before_reset_password', $user);
|
||||
|
||||
// 비밀번호 업데이트
|
||||
$this->userRepository->update($user, [
|
||||
'password' => Hash::make($password),
|
||||
]);
|
||||
// 비밀번호 업데이트
|
||||
$this->userRepository->update($user, [
|
||||
'password' => Hash::make($password),
|
||||
]);
|
||||
|
||||
// 사용된 토큰 삭제
|
||||
$record->delete();
|
||||
// 사용된 토큰 삭제
|
||||
$record->delete();
|
||||
});
|
||||
|
||||
// Hook 발생 (비밀번호 변경 완료) — 알림 발송은 NotificationHookListener가 처리
|
||||
HookManager::doAction('core.auth.after_password_changed', $user);
|
||||
|
||||
@@ -11,6 +11,7 @@ use App\Models\Menu;
|
||||
use App\Models\User;
|
||||
use Illuminate\Database\Eloquent\Collection;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
class MenuService
|
||||
@@ -182,13 +183,16 @@ class MenuService
|
||||
]);
|
||||
}
|
||||
|
||||
// Hook: 메뉴 삭제 전
|
||||
HookManager::doAction('core.menu.before_delete', $menu);
|
||||
// 역할 연결만 끊기고 메뉴는 남는 상태를 막기 위해 두 단계를 하나로 묶는다.
|
||||
$result = DB::transaction(function () use ($menu) {
|
||||
// Hook: 메뉴 삭제 전
|
||||
HookManager::doAction('core.menu.before_delete', $menu);
|
||||
|
||||
// 역할 연결 해제 (명시적 삭제 - CASCADE 의존 금지)
|
||||
$menu->roles()->detach();
|
||||
// 역할 연결 해제 (명시적 삭제 - CASCADE 의존 금지)
|
||||
$menu->roles()->detach();
|
||||
|
||||
$result = $this->menuRepository->delete($menu);
|
||||
return $this->menuRepository->delete($menu);
|
||||
});
|
||||
|
||||
// Hook: 메뉴 삭제 후
|
||||
HookManager::doAction('core.menu.after_delete', $menu->id);
|
||||
|
||||
@@ -93,6 +93,27 @@ class NotificationLogService
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 보존 기간이 지난 발송 이력을 정리합니다 (자동 파기).
|
||||
*
|
||||
* 운영자가 고른 ID 를 지우는 bulkDelete 와는 별개의 훅을 발행한다 — 자동 파기는
|
||||
* 대상을 기간으로 정하고 사람 없이 예약 실행되므로, 대화형 가드를 전제한 훅에
|
||||
* 얹으면 예약이 그 가드에 걸린다. 확장은 이 훅으로 자기 처리를 붙인다.
|
||||
*
|
||||
* @param int $days 보존 기간 (일)
|
||||
* @return int 삭제된 건수
|
||||
*/
|
||||
public function prune(int $days): int
|
||||
{
|
||||
HookManager::doAction('core.notification_log.before_prune', $days);
|
||||
|
||||
$count = $this->repository->deleteOlderThan($days);
|
||||
|
||||
HookManager::doAction('core.notification_log.after_prune', $days, $count);
|
||||
|
||||
return $count;
|
||||
}
|
||||
|
||||
/**
|
||||
* 다건 삭제합니다.
|
||||
*
|
||||
|
||||
@@ -5,6 +5,7 @@ namespace App\Services;
|
||||
use App\Extension\HookManager;
|
||||
use App\Extension\PluginManager;
|
||||
use App\Extension\TemplateManager;
|
||||
use App\Support\ExtensionSettingsMirror;
|
||||
use App\Support\SensitiveSettingMask;
|
||||
use App\Traits\FiltersFrontendSchema;
|
||||
use App\Traits\NormalizesSettingsData;
|
||||
@@ -189,6 +190,10 @@ class PluginSettingsService
|
||||
// 캐시 초기화
|
||||
if ($result) {
|
||||
unset($this->settingsCache[$identifier]);
|
||||
|
||||
// 같은 프로세스의 config 미러도 즉시 다시 채운다 (공개이슈 #109) —
|
||||
// 이 호출이 없으면 상주 프로세스가 저장 후에도 옛 값을 계속 읽는다.
|
||||
app(ExtensionSettingsMirror::class)->refreshPlugin($identifier);
|
||||
}
|
||||
|
||||
// After 훅
|
||||
@@ -247,6 +252,10 @@ class PluginSettingsService
|
||||
// 캐시 초기화
|
||||
unset($this->settingsCache[$identifier]);
|
||||
|
||||
// 초기화도 값을 바꾸는 쓰기다 — 미러를 두면 같은 프로세스가 초기화 전 값을
|
||||
// 계속 읽는다 (저장 경로와 동일 결함, 공개이슈 #109).
|
||||
app(ExtensionSettingsMirror::class)->refreshPlugin($identifier);
|
||||
|
||||
// After 훅
|
||||
HookManager::doAction('core.plugin_settings.after_reset', $identifier);
|
||||
|
||||
|
||||
@@ -11,6 +11,7 @@ use App\Models\User;
|
||||
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
|
||||
use Illuminate\Database\Eloquent\Collection;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
class RoleService
|
||||
@@ -183,16 +184,20 @@ class RoleService
|
||||
throw new ExtensionOwnedRoleDeleteException;
|
||||
}
|
||||
|
||||
// 훅: 삭제 전
|
||||
HookManager::doAction('core.role.before_delete', $role);
|
||||
// 관계 해제 후 삭제가 실패하면 그 역할을 가진 사용자 전원이 권한만 잃고
|
||||
// 역할은 그대로 남는다. 전 단계를 하나로 묶는다.
|
||||
$result = DB::transaction(function () use ($role) {
|
||||
// 훅: 삭제 전
|
||||
HookManager::doAction('core.role.before_delete', $role);
|
||||
|
||||
// 관계 해제 (명시적 삭제 - CASCADE 의존 금지)
|
||||
$this->roleRepository->detachAllPermissions($role);
|
||||
$role->menus()->detach();
|
||||
$role->users()->detach();
|
||||
// 관계 해제 (명시적 삭제 - CASCADE 의존 금지)
|
||||
$this->roleRepository->detachAllPermissions($role);
|
||||
$role->menus()->detach();
|
||||
$role->users()->detach();
|
||||
|
||||
// 역할 삭제
|
||||
$result = $this->roleRepository->delete($role);
|
||||
// 역할 삭제
|
||||
return $this->roleRepository->delete($role);
|
||||
});
|
||||
|
||||
// 훅: 삭제 후
|
||||
HookManager::doAction('core.role.after_delete', $role->id);
|
||||
|
||||
@@ -122,13 +122,16 @@ class ScheduleService
|
||||
public function delete(Schedule $schedule): bool
|
||||
{
|
||||
try {
|
||||
// before_delete 훅 실행
|
||||
HookManager::doAction('core.schedule.before_delete', $schedule);
|
||||
// 이력만 지워지고 스케줄은 남는 상태를 막기 위해 두 단계를 하나로 묶는다.
|
||||
$result = DB::transaction(function () use ($schedule) {
|
||||
// before_delete 훅 실행
|
||||
HookManager::doAction('core.schedule.before_delete', $schedule);
|
||||
|
||||
// 실행 이력 삭제 (명시적 삭제 - CASCADE 의존 금지)
|
||||
$schedule->histories()->delete();
|
||||
// 실행 이력 삭제 (명시적 삭제 - CASCADE 의존 금지)
|
||||
$schedule->histories()->delete();
|
||||
|
||||
$result = $this->scheduleRepository->delete($schedule);
|
||||
return $this->scheduleRepository->delete($schedule);
|
||||
});
|
||||
|
||||
// after_delete 훅 실행
|
||||
HookManager::doAction('core.schedule.after_delete', $schedule->id);
|
||||
@@ -488,6 +491,26 @@ class ScheduleService
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 보존 기간이 지난 실행 이력을 정리합니다 (자동 파기).
|
||||
*
|
||||
* 운영자가 고른 ID 를 지우는 bulkDeleteHistory 와 달리 대상을 기간으로 정하고
|
||||
* 사람 없이 예약 실행되므로 별개의 훅을 발행합니다.
|
||||
*
|
||||
* @param int $days 보존 기간 (일)
|
||||
* @return int 삭제된 건수
|
||||
*/
|
||||
public function pruneHistory(int $days): int
|
||||
{
|
||||
HookManager::doAction('core.schedule.before_prune_history', $days);
|
||||
|
||||
$deletedCount = $this->historyRepository->deleteOlderThan($days);
|
||||
|
||||
HookManager::doAction('core.schedule.after_prune_history', $days, $deletedCount);
|
||||
|
||||
return $deletedCount;
|
||||
}
|
||||
|
||||
/**
|
||||
* 활성화된 스케줄들을 조회합니다.
|
||||
*
|
||||
|
||||
@@ -9,6 +9,7 @@ use App\Extension\HookManager;
|
||||
use App\Http\Resources\AttachmentResource;
|
||||
use App\Seo\Contracts\SeoCacheManagerInterface;
|
||||
use App\Support\ConfigCacheHelper;
|
||||
use App\Support\ExtensionSettingsMirror;
|
||||
use App\Support\OpcacheStatus;
|
||||
use Illuminate\Support\Facades\Artisan;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
@@ -43,6 +44,11 @@ class SettingsService
|
||||
{
|
||||
$this->cache->forget('settings.system');
|
||||
ConfigCacheHelper::rebuild();
|
||||
|
||||
// 같은 프로세스의 in-memory 미러도 즉시 다시 채운다 (공개이슈 #109).
|
||||
// 이 호출이 없으면 상주 프로세스(큐 워커·schedule:work·Reverb)는 저장 후에도
|
||||
// 부팅 시점의 옛 값을 영원히 읽는다 — FPM 에서만 드러나지 않는 결함이다.
|
||||
app(ExtensionSettingsMirror::class)->refreshCore();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -703,7 +709,9 @@ class SettingsService
|
||||
$result = $this->configRepository->set($key, $value);
|
||||
|
||||
if ($result) {
|
||||
$this->cache->forget('settings.system');
|
||||
// 인라인 무효화 대신 공통 경로를 탄다 — saveSettings/saveAdvancedSettings 와
|
||||
// 같은 처리를 받아야 미러 재채움·디스크 config 캐시 재생성이 빠지지 않는다.
|
||||
$this->invalidateSettingsCache();
|
||||
}
|
||||
|
||||
// After 훅
|
||||
@@ -738,7 +746,9 @@ class SettingsService
|
||||
$result = $this->configRepository->restore($backupPath);
|
||||
|
||||
if ($result) {
|
||||
$this->cache->forget('settings.system');
|
||||
// 복원도 설정 전체를 갈아엎는 쓰기다 — 캐시만 비우고 미러를 두면
|
||||
// 같은 프로세스가 복원 전 값을 계속 읽는다 (저장 경로와 동일 결함, 공개이슈 #109).
|
||||
$this->invalidateSettingsCache();
|
||||
}
|
||||
|
||||
return $result;
|
||||
|
||||
+255
-52
@@ -10,6 +10,7 @@ use App\Extension\HookManager;
|
||||
use App\Helpers\PermissionHelper;
|
||||
use App\Helpers\TimezoneHelper;
|
||||
use App\Models\ActivityLog;
|
||||
use App\Models\Attachment;
|
||||
use App\Models\User;
|
||||
use Exception;
|
||||
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
|
||||
@@ -17,6 +18,7 @@ use Illuminate\Database\Eloquent\Collection;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
class UserService
|
||||
@@ -170,6 +172,23 @@ class UserService
|
||||
}
|
||||
}
|
||||
|
||||
// 관리자가 상태만 '탈퇴'로 바꾸는 경로도 정식 탈퇴 로직으로 통일한다.
|
||||
//
|
||||
// 여기서 status/withdrawn_at 을 먼저 저장하면 withdraw() 의 멱등 가드가
|
||||
// 이미 탈퇴한 계정으로 판정해 익명화와 훅이 조용히 생략된다.
|
||||
// 따라서 상태 필드는 제거하고, 다른 필드 갱신을 마친 뒤 withdrawUser() 에 위임한다.
|
||||
$withdrawViaStatus = isset($data['status'])
|
||||
&& $data['status'] === UserStatus::Withdrawn->value
|
||||
&& ! $user->isWithdrawn();
|
||||
|
||||
if ($withdrawViaStatus) {
|
||||
unset($data['status']);
|
||||
|
||||
// 차단 대상(관리자/수퍼관리자)이면 다른 필드도 저장되지 않아야 하므로
|
||||
// 갱신 전에 가드를 평가한다.
|
||||
$this->assertWithdrawable($user);
|
||||
}
|
||||
|
||||
// 상태 변경 감지 및 타임스탬프 자동 설정
|
||||
$oldStatus = $user->status;
|
||||
$newStatus = $data['status'] ?? null;
|
||||
@@ -178,7 +197,8 @@ class UserService
|
||||
$newStatusEnum = UserStatus::from($newStatus);
|
||||
$data = match ($newStatusEnum) {
|
||||
UserStatus::Blocked => array_merge($data, ['blocked_at' => now()]),
|
||||
UserStatus::Withdrawn => array_merge($data, ['withdrawn_at' => now()]),
|
||||
// 탈퇴는 위 위임 경로(withdrawUser)가 전담하므로 여기로는 도달하지 않는다.
|
||||
UserStatus::Withdrawn => $data,
|
||||
UserStatus::Active => array_merge($data, ['blocked_at' => null, 'withdrawn_at' => null]),
|
||||
UserStatus::Inactive => $data,
|
||||
};
|
||||
@@ -187,22 +207,45 @@ class UserService
|
||||
// 스냅샷 캡처 (ChangeDetector용)
|
||||
$snapshot = $user->toArray();
|
||||
|
||||
$this->userRepository->update($user, $data);
|
||||
// 탈퇴 위임 시 아바타는 커밋 후에 지운다 (트랜잭션 안에서 지우면 롤백돼도 파일은 안 돌아온다).
|
||||
$avatarAttachment = $withdrawViaStatus ? $user->avatarAttachment : null;
|
||||
|
||||
// 상태가 Active 외로 변경되었으면 토큰 삭제 (즉시 로그아웃)
|
||||
if ($newStatus && $newStatus !== $oldStatus && $newStatus !== UserStatus::Active->value) {
|
||||
$user->tokens()->delete();
|
||||
}
|
||||
// 프로필 갱신·토큰 정리·역할 동기화가 서로 어긋나지 않도록 하나로 묶는다.
|
||||
//
|
||||
// 상태 변경 경유 탈퇴는 **탈퇴까지 같은 트랜잭션**에 넣는다 — 프로필 갱신을
|
||||
// 먼저 커밋하고 탈퇴를 따로 커밋하면, 탈퇴가 실패했을 때 이름·이메일 변경만
|
||||
// 남아 "전부 성공하거나 전부 취소" 가 그 경로에서만 깨진다.
|
||||
DB::transaction(function () use ($user, $data, $newStatus, $oldStatus, $roleIds, $withdrawViaStatus) {
|
||||
$this->userRepository->update($user, $data);
|
||||
|
||||
// 역할 동기화
|
||||
// 상태가 Active 외로 변경되었으면 토큰 삭제 (즉시 로그아웃)
|
||||
if ($newStatus && $newStatus !== $oldStatus && $newStatus !== UserStatus::Active->value) {
|
||||
$user->tokens()->delete();
|
||||
}
|
||||
|
||||
// 역할 동기화
|
||||
if ($roleIds !== null) {
|
||||
$user->roles()->sync($roleIds);
|
||||
}
|
||||
|
||||
// 익명화 + before_withdraw 훅 + 연계 데이터 정리 (본인 탈퇴와 동일 코드)
|
||||
if ($withdrawViaStatus) {
|
||||
$this->performWithdrawWrites($user);
|
||||
}
|
||||
});
|
||||
|
||||
// 커밋 후 부수효과 (캐시는 롤백 대상이 아니다)
|
||||
if ($roleIds !== null) {
|
||||
$user->roles()->sync($roleIds);
|
||||
$user->flushPermissionCaches();
|
||||
}
|
||||
|
||||
// After 훅: 사용자 객체와 원본 데이터, 스냅샷 전달
|
||||
HookManager::doAction('core.user.after_update', $user, $originalData, $snapshot);
|
||||
|
||||
if ($withdrawViaStatus) {
|
||||
$this->runWithdrawAfterEffects($user, $avatarAttachment);
|
||||
}
|
||||
|
||||
// 비밀번호 변경 시 알림 훅 발화 — 발송은 NotificationHookListener가 처리
|
||||
if ($passwordChanged) {
|
||||
HookManager::doAction('core.auth.after_password_changed', $user);
|
||||
@@ -214,12 +257,93 @@ class UserService
|
||||
throw $e;
|
||||
}
|
||||
|
||||
if ($e instanceof CannotDeleteSuperAdminException) {
|
||||
throw $e;
|
||||
}
|
||||
|
||||
throw ValidationException::withMessages([
|
||||
'general' => [__('user.update_failed', ['error' => $e->getMessage()])],
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 탈퇴 가능한 계정인지 검사합니다.
|
||||
*
|
||||
* 탈퇴 경로(본인 탈퇴 / 관리자 상태 변경 / 일괄 상태 변경)가 모두 같은 기준을
|
||||
* 쓰도록 한 곳에 둡니다 — 한쪽만 느슨하면 그 경로가 우회로가 됩니다.
|
||||
*
|
||||
* @param User $user 검사 대상 사용자
|
||||
*
|
||||
* @throws CannotDeleteSuperAdminException 슈퍼 관리자인 경우
|
||||
* @throws ValidationException 관리자 역할을 가진 경우
|
||||
*/
|
||||
private function assertWithdrawable(User $user): void
|
||||
{
|
||||
// 슈퍼 관리자는 탈퇴 불가
|
||||
if ($user->isSuperAdmin()) {
|
||||
throw new CannotDeleteSuperAdminException;
|
||||
}
|
||||
|
||||
// 관리자 역할을 가진 계정은 탈퇴 방지
|
||||
if ($user->isAdmin()) {
|
||||
throw ValidationException::withMessages([
|
||||
'general' => [__('user.withdraw_admin_forbidden')],
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 탈퇴의 DB 변경만 수행합니다 (호출자가 연 트랜잭션 안에서 실행).
|
||||
*
|
||||
* 관리자가 상태 변경으로 탈퇴시키는 경로는 프로필 갱신과 탈퇴를 **한 트랜잭션**으로
|
||||
* 묶어야 한다 — 두 번에 나눠 커밋하면 탈퇴가 실패했을 때 프로필 변경만 남는다.
|
||||
* 그래서 DB 변경분을 이 메서드로 떼어 두 경로가 같은 코드를 공유한다.
|
||||
*
|
||||
* @param User $user 탈퇴 처리할 사용자 모델
|
||||
* @return bool 탈퇴 처리 성공 여부
|
||||
*/
|
||||
private function performWithdrawWrites(User $user): bool
|
||||
{
|
||||
// 훅 실행 (탈퇴 전)
|
||||
HookManager::doAction('core.user.before_withdraw', $user);
|
||||
|
||||
// 약관 동의 이력 삭제 (명시적 삭제 - CASCADE 의존 금지)
|
||||
$user->consents()->delete();
|
||||
|
||||
// 토큰 삭제 (로그아웃 처리)
|
||||
$user->tokens()->delete();
|
||||
|
||||
// 탈퇴 처리 (suffix 추가 및 상태 변경)
|
||||
return $user->withdraw();
|
||||
}
|
||||
|
||||
/**
|
||||
* 탈퇴 커밋 후 부수효과를 수행합니다.
|
||||
*
|
||||
* @param User $user 탈퇴 처리된 사용자 모델
|
||||
* @param Attachment|null $avatarAttachment 탈퇴 전 캡처한 아바타 첨부
|
||||
*/
|
||||
private function runWithdrawAfterEffects(User $user, $avatarAttachment): void
|
||||
{
|
||||
// 아바타 파일 삭제는 실패해도 탈퇴를 되돌리지 않는다
|
||||
// (고아 파일은 비파괴이고, 탈퇴를 되살리는 쪽이 훨씬 해롭다).
|
||||
if ($avatarAttachment) {
|
||||
try {
|
||||
$this->attachmentService->delete($avatarAttachment->id);
|
||||
} catch (Exception $e) {
|
||||
Log::warning('탈퇴 아바타 삭제 실패', [
|
||||
'user_id' => $user->id,
|
||||
'attachment_id' => $avatarAttachment->id,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
// 훅 실행 (탈퇴 후)
|
||||
HookManager::doAction('core.user.after_withdraw', $user);
|
||||
}
|
||||
|
||||
/**
|
||||
* 사용자를 탈퇴 처리합니다.
|
||||
*
|
||||
@@ -235,39 +359,19 @@ class UserService
|
||||
public function withdrawUser(User $user): bool
|
||||
{
|
||||
try {
|
||||
// 슈퍼 관리자는 탈퇴 불가
|
||||
if ($user->isSuperAdmin()) {
|
||||
throw new CannotDeleteSuperAdminException;
|
||||
}
|
||||
// 슈퍼 관리자 / 관리자 탈퇴 차단 (전 탈퇴 경로 공통 기준)
|
||||
$this->assertWithdrawable($user);
|
||||
|
||||
// 관리자 역할을 가진 계정은 탈퇴 방지
|
||||
if ($user->isAdmin()) {
|
||||
throw ValidationException::withMessages([
|
||||
'general' => [__('user.withdraw_admin_forbidden')],
|
||||
]);
|
||||
}
|
||||
|
||||
// 훅 실행 (탈퇴 전)
|
||||
HookManager::doAction('core.user.before_withdraw', $user);
|
||||
|
||||
// 약관 동의 이력 삭제 (명시적 삭제 - CASCADE 의존 금지)
|
||||
$user->consents()->delete();
|
||||
|
||||
// 아바타 Attachment 삭제 (다형성 관계)
|
||||
// 아바타는 파일 삭제를 동반하므로 트랜잭션 밖(커밋 후)에서 처리한다 —
|
||||
// 트랜잭션 안에서 지우면 롤백되어도 파일은 돌아오지 않는다.
|
||||
$avatarAttachment = $user->avatarAttachment;
|
||||
if ($avatarAttachment) {
|
||||
$this->attachmentService->delete($avatarAttachment->id);
|
||||
}
|
||||
|
||||
// 토큰 삭제 (로그아웃 처리)
|
||||
$user->tokens()->delete();
|
||||
// DB 변경은 전부 성공하거나 전부 취소된다 (공개이슈 #112).
|
||||
// 마지막 단계인 withdraw() 가 실패하면 동의 이력·토큰 삭제도 함께 되돌아간다.
|
||||
$result = DB::transaction(fn () => $this->performWithdrawWrites($user));
|
||||
|
||||
// 탈퇴 처리 (suffix 추가 및 상태 변경)
|
||||
$result = $user->withdraw();
|
||||
|
||||
// 훅 실행 (탈퇴 후)
|
||||
if ($result) {
|
||||
HookManager::doAction('core.user.after_withdraw', $user);
|
||||
$this->runWithdrawAfterEffects($user, $avatarAttachment);
|
||||
}
|
||||
|
||||
return $result;
|
||||
@@ -310,27 +414,42 @@ class UserService
|
||||
// 삭제 전 사용자 데이터 보관 (after_delete 훅에서 사용)
|
||||
$userData = $user->only(['id', 'uuid', 'name', 'email']);
|
||||
|
||||
// Before 훅
|
||||
HookManager::doAction('core.user.before_delete', $user);
|
||||
// 아바타는 파일 삭제를 동반하므로 커밋 후에 처리한다 (롤백되어도 파일은 안 돌아온다).
|
||||
$avatarAttachment = $user->avatarAttachment;
|
||||
|
||||
// 역할 연결 해제 (명시적 삭제 - CASCADE 의존 금지)
|
||||
$user->roles()->detach();
|
||||
// 마지막 delete 가 FK 등으로 실패하면 역할·동의·토큰만 사라지고 계정은 남는
|
||||
// 껍데기 활성 계정이 된다 (실회귀 이력 존재). 전 단계를 하나로 묶는다.
|
||||
$result = DB::transaction(function () use ($user) {
|
||||
// Before 훅
|
||||
HookManager::doAction('core.user.before_delete', $user);
|
||||
|
||||
// 역할 연결 해제 (명시적 삭제 - CASCADE 의존 금지)
|
||||
$user->roles()->detach();
|
||||
|
||||
// 약관 동의 이력 삭제
|
||||
$user->consents()->delete();
|
||||
|
||||
// API 토큰 삭제
|
||||
$user->tokens()->delete();
|
||||
|
||||
return $this->userRepository->delete($user);
|
||||
});
|
||||
|
||||
// 커밋 성공 후 부수효과
|
||||
$user->flushPermissionCaches();
|
||||
|
||||
// 약관 동의 이력 삭제
|
||||
$user->consents()->delete();
|
||||
|
||||
// API 토큰 삭제
|
||||
$user->tokens()->delete();
|
||||
|
||||
// 아바타 Attachment 삭제 (다형성 관계)
|
||||
$avatarAttachment = $user->avatarAttachment;
|
||||
if ($avatarAttachment) {
|
||||
$this->attachmentService->delete($avatarAttachment->id);
|
||||
try {
|
||||
$this->attachmentService->delete($avatarAttachment->id);
|
||||
} catch (Exception $e) {
|
||||
Log::warning('사용자 삭제 아바타 정리 실패', [
|
||||
'user_id' => $userData['id'] ?? null,
|
||||
'attachment_id' => $avatarAttachment->id,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
$result = $this->userRepository->delete($user);
|
||||
|
||||
// After 훅: 삭제된 사용자 데이터 전달
|
||||
HookManager::doAction('core.user.after_delete', $userData);
|
||||
|
||||
@@ -579,6 +698,12 @@ class UserService
|
||||
|
||||
$statusEnum = UserStatus::from($status);
|
||||
|
||||
// 일괄 '탈퇴'는 건별 정식 탈퇴로 전환한다 — 상태 컬럼만 바꾸면 익명화와
|
||||
// before/after_withdraw 훅이 통째로 생략되어, 본인 탈퇴와 결과가 달라진다.
|
||||
if ($statusEnum === UserStatus::Withdrawn) {
|
||||
return $this->bulkWithdraw($uuids, $status);
|
||||
}
|
||||
|
||||
// UUID → 정수 ID 변환 (내부 쿼리용)
|
||||
$userIds = $this->userRepository->getIdsByUuids($uuids);
|
||||
|
||||
@@ -588,7 +713,8 @@ class UserService
|
||||
$updateData = ['status' => $statusEnum->value];
|
||||
$updateData = match ($statusEnum) {
|
||||
UserStatus::Blocked => array_merge($updateData, ['blocked_at' => now()]),
|
||||
UserStatus::Withdrawn => array_merge($updateData, ['withdrawn_at' => now()]),
|
||||
// 탈퇴는 위에서 건별 withdrawUser() 로 분기하므로 여기로는 도달하지 않는다.
|
||||
UserStatus::Withdrawn => $updateData,
|
||||
UserStatus::Active => array_merge($updateData, ['blocked_at' => null, 'withdrawn_at' => null]),
|
||||
UserStatus::Inactive => $updateData,
|
||||
};
|
||||
@@ -608,6 +734,83 @@ class UserService
|
||||
|
||||
return [
|
||||
'updated_count' => $updatedCount,
|
||||
'failed_count' => 0,
|
||||
'failed_reasons' => [],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 탈퇴 실패 예외를 운영자에게 보여줄 한 줄 사유로 바꿉니다.
|
||||
*
|
||||
* @param Exception $e 탈퇴 시도에서 발생한 예외
|
||||
* @return string 운영자에게 보여줄 실패 사유
|
||||
*/
|
||||
private function describeWithdrawFailure(Exception $e): string
|
||||
{
|
||||
if ($e instanceof ValidationException) {
|
||||
$first = collect($e->errors())->flatten()->first();
|
||||
|
||||
if (is_string($first) && $first !== '') {
|
||||
return $first;
|
||||
}
|
||||
}
|
||||
|
||||
if ($e instanceof CannotDeleteSuperAdminException) {
|
||||
return __('exceptions.cannot_delete_super_admin');
|
||||
}
|
||||
|
||||
// 알 수 없는 예외의 원문 메시지는 사유로 쓰지 않는다 — 내부 사정(SQL·경로·클래스명)이
|
||||
// 운영자 화면으로 새고, 화면 문구 조립에서 파라미터 구분자로 쓰이는 문자(`|` `&` `=`)가
|
||||
// 섞이면 안내가 잘린다. 사유는 언어 파일이 소유하는 문구로만 구성한다.
|
||||
return __('user.withdraw_failed_unknown');
|
||||
}
|
||||
|
||||
/**
|
||||
* 일괄 탈퇴를 건별 정식 탈퇴로 수행합니다.
|
||||
*
|
||||
* @param array<int, string> $uuids 대상 사용자 UUID 배열
|
||||
* @param string $status 요청 상태값 (훅 전달용)
|
||||
* @return array{updated_count: int, failed_count: int, failed_reasons: array<int, string>} 처리 결과
|
||||
*/
|
||||
private function bulkWithdraw(array $uuids, string $status): array
|
||||
{
|
||||
$updatedCount = 0;
|
||||
$failedCount = 0;
|
||||
$failedReasons = [];
|
||||
|
||||
foreach ($uuids as $uuid) {
|
||||
$user = $this->userRepository->findByUuid($uuid);
|
||||
|
||||
if (! $user) {
|
||||
$failedCount++;
|
||||
$failedReasons[] = __('user.not_found');
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
$this->withdrawUser($user);
|
||||
$updatedCount++;
|
||||
} catch (Exception $e) {
|
||||
$failedCount++;
|
||||
$failedReasons[] = $this->describeWithdrawFailure($e);
|
||||
|
||||
Log::warning('일괄 탈퇴 건 실패', [
|
||||
'uuid' => $uuid,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
// after_bulk_update 훅 실행
|
||||
HookManager::doAction('sirsoft-core.user.after_bulk_update', $uuids, $status, $updatedCount);
|
||||
|
||||
// 사유를 함께 돌려주지 않으면 화면은 "몇 건 실패" 까지만 말할 수 있다 —
|
||||
// 운영자는 왜 안 됐는지 알 방법이 없어 같은 조작을 반복하게 된다.
|
||||
return [
|
||||
'updated_count' => $updatedCount,
|
||||
'failed_count' => $failedCount,
|
||||
'failed_reasons' => array_values(array_unique($failedReasons)),
|
||||
];
|
||||
}
|
||||
|
||||
|
||||
@@ -16,9 +16,13 @@ use Illuminate\Support\Facades\Log;
|
||||
* 한 번 비워진 뒤 재생성되지 않아 성능 이점이 영구히 사라진다 — 이를 단일 SSoT 로 막는다.
|
||||
*
|
||||
* 정책: 환경 무관 항상 재생성. config:cache 는 그 자체로 부팅 비용을
|
||||
* 절감하고, G7 설정은 config 캐시에 박제되지 않고 매 요청 SettingsServiceProvider /
|
||||
* CoreServiceProvider 의 런타임 Config::set() 으로 재주입되므로(설정 stale 없음),
|
||||
* 항상 켜두는 것이 이득이다. local 개발 시 config/*.php 수정이 즉시 반영되지 않는 점은
|
||||
* 절감하고, G7 설정은 config 캐시에 박제되지 않고 부팅 때 SettingsServiceProvider /
|
||||
* CoreServiceProvider 의 런타임 Config::set() 으로 재주입되므로 항상 켜두는 것이 이득이다.
|
||||
*
|
||||
* 주의: "매 요청 재주입되므로 stale 없음" 은 FPM 전제였다. 큐 워커·schedule:work·Reverb
|
||||
* 처럼 프로세스가 상주하는 환경에서는 부팅이 한 번뿐이라 저장 후에도 옛 값이 남는다.
|
||||
* 그래서 저장 경로가 `ExtensionSettingsMirror` 로 in-memory 미러를 직접 다시 채운다
|
||||
* (docs/backend/admin-settings-access.md "config 미러 갱신 시점" 참조). local 개발 시 config/*.php 수정이 즉시 반영되지 않는 점은
|
||||
* 개발자가 `php artisan config:clear` 로 대응하는 개발자 책임 영역이다.
|
||||
*/
|
||||
class ConfigCacheHelper
|
||||
|
||||
@@ -0,0 +1,310 @@
|
||||
<?php
|
||||
|
||||
namespace App\Support;
|
||||
|
||||
use App\Contracts\Extension\ModuleSettingsInterface;
|
||||
use App\Extension\ModuleManager;
|
||||
use App\Extension\PluginManager;
|
||||
use App\Repositories\JsonConfigRepository;
|
||||
use App\Services\PluginSettingsService;
|
||||
use Illuminate\Support\Facades\Config;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
/**
|
||||
* 설정 config 미러(`g7_settings.*`) 관리자
|
||||
*
|
||||
* `g7_core_settings()` / `g7_module_settings()` / `g7_plugin_settings()` 가 읽는
|
||||
* in-memory config 미러를 채웁니다.
|
||||
*
|
||||
* 종전에는 이 미러가 **부팅 때 한 번만** 채워졌습니다. FPM 은 요청마다 부팅하므로
|
||||
* 문제가 드러나지 않지만, 큐 워커·schedule:work·Reverb 처럼 프로세스가 상주하는
|
||||
* 환경에서는 관리자가 설정을 저장해도 그 프로세스의 미러가 영원히 옛 값으로 남습니다
|
||||
* (공개이슈 #109). 저장 경로에서 이 클래스의 refresh* 를 호출해 같은 프로세스의
|
||||
* 미러를 즉시 다시 채웁니다.
|
||||
*
|
||||
* 민감 항목은 미러에 담지 않습니다 — 민감값이 필요한 서버 코드는 전용 게터
|
||||
* (`plugin_setting()` 등)를 씁니다. 자세한 근거는 docs/backend/admin-settings-access.md 참조.
|
||||
*/
|
||||
class ExtensionSettingsMirror
|
||||
{
|
||||
/**
|
||||
* 코어 설정 카테고리 목록
|
||||
*
|
||||
* @var array<int, string>
|
||||
*/
|
||||
public const CORE_CATEGORIES = [
|
||||
'mail',
|
||||
'general',
|
||||
'security',
|
||||
'debug',
|
||||
'drivers',
|
||||
'cache',
|
||||
'upload',
|
||||
'core_update',
|
||||
'geoip',
|
||||
'seo',
|
||||
'identity',
|
||||
'pagination',
|
||||
];
|
||||
|
||||
/**
|
||||
* 코어 설정 미러(`g7_settings.core`)를 다시 채웁니다.
|
||||
*
|
||||
* @param JsonConfigRepository|null $configRepository 설정 저장소 (미지정 시 새로 생성)
|
||||
*/
|
||||
public function refreshCore(?JsonConfigRepository $configRepository = null): void
|
||||
{
|
||||
// 이 메서드는 SettingsServiceProvider::register() 에서도 호출된다 —
|
||||
// 그 시점은 DI 컨테이너 사용 전이므로 직접 인스턴스화가 유일한 선택지다.
|
||||
$configRepository ??= new JsonConfigRepository;
|
||||
|
||||
$coreSettings = [];
|
||||
|
||||
foreach (self::CORE_CATEGORIES as $category) {
|
||||
$settings = $configRepository->getCategory($category);
|
||||
|
||||
if (! empty($settings)) {
|
||||
$coreSettings[$category] = $settings;
|
||||
}
|
||||
}
|
||||
|
||||
Config::set('g7_settings.core', $coreSettings);
|
||||
}
|
||||
|
||||
/**
|
||||
* 활성 모듈 전체의 설정 미러를 다시 채웁니다.
|
||||
*/
|
||||
public function refreshAllModules(): void
|
||||
{
|
||||
$moduleManager = app(ModuleManager::class);
|
||||
$moduleSettings = [];
|
||||
|
||||
foreach (array_keys($moduleManager->getActiveModules()) as $identifier) {
|
||||
$settings = $this->resolveModuleSettings($identifier);
|
||||
|
||||
if (! empty($settings)) {
|
||||
$moduleSettings[$identifier] = $settings;
|
||||
}
|
||||
}
|
||||
|
||||
Config::set('g7_settings.modules', $moduleSettings);
|
||||
}
|
||||
|
||||
/**
|
||||
* 모듈 하나의 설정 미러를 다시 채웁니다.
|
||||
*
|
||||
* @param string $identifier 모듈 식별자 (예: sirsoft-ecommerce)
|
||||
*/
|
||||
public function refreshModule(string $identifier): void
|
||||
{
|
||||
$settings = $this->resolveModuleSettings($identifier);
|
||||
|
||||
if (empty($settings)) {
|
||||
Config::set('g7_settings.modules.'.$identifier, []);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
Config::set('g7_settings.modules.'.$identifier, $settings);
|
||||
}
|
||||
|
||||
/**
|
||||
* 활성 플러그인 전체의 설정 미러를 다시 채웁니다.
|
||||
*/
|
||||
public function refreshAllPlugins(): void
|
||||
{
|
||||
$pluginManager = app(PluginManager::class);
|
||||
$pluginSettings = [];
|
||||
|
||||
foreach (array_keys($pluginManager->getActivePlugins()) as $identifier) {
|
||||
$settings = $this->resolvePluginSettings($identifier);
|
||||
|
||||
if (! empty($settings)) {
|
||||
$pluginSettings[$identifier] = $settings;
|
||||
}
|
||||
}
|
||||
|
||||
Config::set('g7_settings.plugins', $pluginSettings);
|
||||
}
|
||||
|
||||
/**
|
||||
* 플러그인 하나의 설정 미러를 다시 채웁니다.
|
||||
*
|
||||
* @param string $identifier 플러그인 식별자 (예: sirsoft-gdpr)
|
||||
*/
|
||||
public function refreshPlugin(string $identifier): void
|
||||
{
|
||||
Config::set('g7_settings.plugins.'.$identifier, $this->resolvePluginSettings($identifier));
|
||||
}
|
||||
|
||||
/**
|
||||
* 모듈 설정 서비스에서 미러에 담을 값을 만듭니다.
|
||||
*
|
||||
* 확장 하나가 실패해도 부팅/저장을 중단시키지 않습니다.
|
||||
*
|
||||
* @param string $identifier 모듈 식별자
|
||||
* @return array<string, mixed> 미러 값 (민감 항목 제외)
|
||||
*/
|
||||
private function resolveModuleSettings(string $identifier): array
|
||||
{
|
||||
try {
|
||||
$settingsService = $this->resolveModuleSettingsService($identifier);
|
||||
|
||||
if (! $settingsService instanceof ModuleSettingsInterface) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return $this->stripSensitive(
|
||||
$settingsService->getAllSettings(),
|
||||
$this->resolveModuleSchema($identifier),
|
||||
);
|
||||
} catch (\Throwable $e) {
|
||||
Log::warning("모듈 환경설정 로딩 실패: {$identifier}", [
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 플러그인 설정에서 미러에 담을 값을 만듭니다.
|
||||
*
|
||||
* 종전에는 setting.json 을 raw 로 읽어 defaults 병합도 정규화도 없었고,
|
||||
* 암호문이 그대로 실렸습니다. 이제 PluginSettingsService 를 경유해 값의 형태를
|
||||
* 전용 게터와 맞추되, 민감 항목은 **키 자체를 담지 않습니다**.
|
||||
*
|
||||
* @param string $identifier 플러그인 식별자
|
||||
* @return array<string, mixed> 미러 값 (민감 항목 제외)
|
||||
*/
|
||||
private function resolvePluginSettings(string $identifier): array
|
||||
{
|
||||
try {
|
||||
$pluginManager = app(PluginManager::class);
|
||||
$plugin = $pluginManager->getPlugin($identifier);
|
||||
|
||||
if (! $plugin) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$settings = app(PluginSettingsService::class)->get($identifier);
|
||||
|
||||
if (! is_array($settings)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return $this->stripSensitive($settings, $plugin->getSettingsSchema());
|
||||
} catch (\Throwable $e) {
|
||||
Log::warning("플러그인 환경설정 로딩 실패: {$identifier}", [
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 스키마에서 `sensitive: true` 로 선언된 필드를 제거합니다.
|
||||
*
|
||||
* 미러는 봇 전용 화면 생성기가 키 제한 없이 조회하는 경로이므로, 민감값이 실리면
|
||||
* 레이아웃이 그 키를 참조하는 순간 평문이 봇 HTML 로 나갑니다. 브라우저 경로는
|
||||
* 애초에 제외 중이라 화면만 봐서는 드러나지 않는 비대칭입니다.
|
||||
*
|
||||
* @param array<string, mixed> $settings 설정 배열
|
||||
* @param array<string, mixed> $schema 설정 스키마
|
||||
* @return array<string, mixed> 민감 항목이 제거된 설정
|
||||
*/
|
||||
private function stripSensitive(array $settings, array $schema): array
|
||||
{
|
||||
foreach ($schema as $field => $config) {
|
||||
if (! is_array($config)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($config['sensitive'] ?? false) {
|
||||
unset($settings[$field]);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
// 카테고리형 스키마 (category.field) 지원
|
||||
if (! isset($settings[$field]) || ! is_array($settings[$field])) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$nested = array_filter($config, 'is_array');
|
||||
|
||||
if ($nested !== []) {
|
||||
$settings[$field] = $this->stripSensitive($settings[$field], $nested);
|
||||
}
|
||||
}
|
||||
|
||||
return $settings;
|
||||
}
|
||||
|
||||
/**
|
||||
* 모듈의 설정 스키마를 조회합니다.
|
||||
*
|
||||
* @param string $identifier 모듈 식별자
|
||||
* @return array<string, mixed> 설정 스키마 (없으면 빈 배열)
|
||||
*/
|
||||
private function resolveModuleSchema(string $identifier): array
|
||||
{
|
||||
$module = app(ModuleManager::class)->getModule($identifier);
|
||||
|
||||
if (! $module || ! method_exists($module, 'getSettingsSchema')) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$schema = $module->getSettingsSchema();
|
||||
|
||||
return is_array($schema) ? $schema : [];
|
||||
}
|
||||
|
||||
/**
|
||||
* 모듈의 환경설정 서비스를 찾아 인스턴스화합니다.
|
||||
*
|
||||
* 다음 순서로 설정 서비스를 찾습니다:
|
||||
* 1. 인터페이스 바인딩: Modules\Vendor\Module\Contracts\ModuleSettingsServiceInterface
|
||||
* 2. 구체 클래스: Modules\Vendor\Module\Services\ModuleSettingsService
|
||||
*
|
||||
* @param string $identifier 모듈 식별자 (예: sirsoft-ecommerce)
|
||||
* @return ModuleSettingsInterface|null 설정 서비스 인스턴스
|
||||
*/
|
||||
private function resolveModuleSettingsService(string $identifier): ?ModuleSettingsInterface
|
||||
{
|
||||
// vendor-module 형식을 네임스페이스로 변환
|
||||
$parts = explode('-', $identifier);
|
||||
|
||||
if (count($parts) < 2) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$vendor = ucfirst($parts[0]);
|
||||
$moduleName = ucfirst($parts[1]);
|
||||
|
||||
// 1. 인터페이스 바인딩 확인
|
||||
$interfaceClass = "Modules\\{$vendor}\\{$moduleName}\\Contracts\\{$moduleName}SettingsServiceInterface";
|
||||
|
||||
if (app()->bound($interfaceClass)) {
|
||||
$service = app($interfaceClass);
|
||||
|
||||
if ($service instanceof ModuleSettingsInterface) {
|
||||
return $service;
|
||||
}
|
||||
}
|
||||
|
||||
// 2. 구체 클래스 확인
|
||||
$concreteClass = "Modules\\{$vendor}\\{$moduleName}\\Services\\{$moduleName}SettingsService";
|
||||
|
||||
if (class_exists($concreteClass)) {
|
||||
$service = app($concreteClass);
|
||||
|
||||
if ($service instanceof ModuleSettingsInterface) {
|
||||
return $service;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user