fix(core,board,ecommerce,page,kginicis): 정책값 하드코딩·계약 분리 결함 일괄 수정
관리자 환경설정이 값을 저장은 하지만 실제 동작에는 닿지 않던 결함군을 정리했다. 설정 화면(min/max)·저장 검증(FormRequest)·런타임 적용(Service) 세 계층이 각자 리터럴을 들고 있어 서로 조용히 갈라지던 것이 공통 원인이다. 경계값 SSoT 도입: - config/core.php `settings_limits` 를 단일 출처로 두고, FormRequest 는 이 값으로 규칙을 만들고 화면은 설정 응답의 `_meta.limits` 로 같은 값을 받아 바인딩한다. - 게시판·이커머스도 각 모듈 config 의 limits 를 동일 구조로 노출한다. 적용되지 않던 정책을 실제로 적용: - 비밀번호 최소 길이·특수문자 필수(신규 지정 7개 경로. 로그인은 제외 — 정책을 올렸을 때 기존 회원이 자기 계정에 접근조차 못 하는 데드락을 막기 위함) - 계정 잠금 시간 0 = 무한대(전용 컬럼 분리. timestamp 상한과 NULL 규약 때문에 기존 컬럼 재사용이 불가능하다) + 관리자 수동 해제 경로 - 업로드 최대 크기·허용 확장자, 게시판 첨부 개수·댓글 깊이, 페이지 첨부 정책, 장바구니 수량·구매 한도, 마일리지 사용 한도, 주문 부가세 파생 결함: - 큐 Job(sync 드라이버)이 진행 중인 요청의 Request 바인딩을 덮어써, 뒤이어 실행되는 훅 리스너가 헤더를 잃고 조용히 건너뛰었다. Job 이 원 바인딩을 복원하도록 고치고, 전송 헤더가 필요한 리스너는 동기 실행으로 선언한다. - 확장 업데이트 실패 시 상태만 되돌리고 상태 캐시를 비우지 않아, 그 확장의 관리자 화면만 캐시 TTL(기본 하루) 동안 404 로 남았다. 실패 경로에도 무효화를 대칭으로 두고, 빈 목록 자체를 캐시하지 않는다. - 글 작성 시 첨부 파일이 Service 로 전달되지 않아 검증·권한은 통과하고 첨부만 사라졌다. - 환경설정 저장 실패 안내가 내부 설정 키를 그대로 노출했다(105개 항목에 라벨 부여). 재발 방지: - audit 룰 3종(레이아웃 경계 리터럴 / FormRequest 경계 불일치 / Service 재클램프) - 테스트 실행 범위 강제 훅(check-test-scope) - 트러블슈팅 사례 2건(큐 Job 요청 오염 / 확장 상태 캐시 고착) 공개 이슈: gnuboard/g7
This commit is contained in:
1 parent
5d140dfbe6
commit
d17ea28da5
272 files changed
+12431
-1006
No files matched your search
@@ -144,17 +144,21 @@ interface UserRepositoryInterface
|
||||
* `locked_until` 을 현재 시각 + $minutes 로 설정하고 `failed_login_attempts` 를
|
||||
* 0 으로 리셋합니다 (다음 잠금 윈도우 시작점). 잠금 해제 시각을 반환합니다.
|
||||
*
|
||||
* `$minutes <= 0` 은 보안 환경설정의 "0 = 무한대" 규약에 따라 영구 잠금으로 처리하며,
|
||||
* 이때 `locked_until` 은 NULL, `locked_permanently` 는 true 가 되고 null 을 반환합니다.
|
||||
*
|
||||
* @param User $user 잠글 사용자
|
||||
* @param int $minutes 잠금 유지 시간(분)
|
||||
* @return Carbon 잠금 해제 시각
|
||||
* @param int $minutes 잠금 유지 시간(분). 0 이하는 무기한
|
||||
* @return Carbon|null 잠금 해제 시각 (영구 잠금은 null)
|
||||
*/
|
||||
public function lockAccount(User $user, int $minutes): Carbon;
|
||||
public function lockAccount(User $user, int $minutes): ?Carbon;
|
||||
|
||||
/**
|
||||
* 사용자의 모든 로그인 시도 추적 컬럼을 초기화합니다.
|
||||
*
|
||||
* 정상 로그인 성공 시 호출됩니다 (`failed_login_attempts=0`,
|
||||
* `locked_until=null`, `last_failed_login_at=null`).
|
||||
* 정상 로그인 성공 시 또는 관리자 수동 해제 시 호출됩니다
|
||||
* (`failed_login_attempts=0`, `locked_until=null`, `locked_permanently=false`,
|
||||
* `last_failed_login_at=null`).
|
||||
*
|
||||
* @param User $user 대상 사용자
|
||||
*/
|
||||
@@ -163,10 +167,44 @@ interface UserRepositoryInterface
|
||||
/**
|
||||
* 사용자의 계정이 현재 시점에 잠금 상태인지 판정합니다.
|
||||
*
|
||||
* `locked_until` 이 NULL 이거나 현재 시각보다 과거이면 false 를 반환합니다.
|
||||
* `locked_permanently` 가 true 면 항상 true 입니다. 그 외에는 `locked_until` 이
|
||||
* NULL 이거나 현재 시각보다 과거이면 false 를 반환합니다.
|
||||
*
|
||||
* @param User $user 대상 사용자
|
||||
* @return bool 잠금 여부
|
||||
*/
|
||||
public function isLocked(User $user): bool;
|
||||
|
||||
/**
|
||||
* UUID 로 사용자를 찾습니다.
|
||||
*
|
||||
* @param string $uuid 사용자 UUID
|
||||
* @return User|null 찾은 사용자 모델 또는 null
|
||||
*/
|
||||
public function findByUuid(string $uuid): ?User;
|
||||
|
||||
/**
|
||||
* UUID 목록에 해당하는 사용자의 정수 ID 배열을 반환합니다.
|
||||
*
|
||||
* @param array $uuids 사용자 UUID 배열
|
||||
* @return array<int, int> 사용자 ID 배열
|
||||
*/
|
||||
public function getIdsByUuids(array $uuids): array;
|
||||
|
||||
/**
|
||||
* 사용자 ID 목록의 지정 컬럼을 일괄 갱신합니다.
|
||||
*
|
||||
* @param array $ids 사용자 ID 배열
|
||||
* @param array $data 갱신할 컬럼 값
|
||||
* @return int 갱신된 행 수
|
||||
*/
|
||||
public function updateManyByIds(array $ids, array $data): int;
|
||||
|
||||
/**
|
||||
* 사용자 ID 목록의 인증 토큰을 모두 삭제합니다.
|
||||
*
|
||||
* @param array $ids 사용자 ID 배열
|
||||
* @return int 삭제된 토큰 수
|
||||
*/
|
||||
public function deleteTokensByUserIds(array $ids): int;
|
||||
}
|
||||
@@ -12,6 +12,10 @@ use Symfony\Component\HttpKernel\Exception\HttpException;
|
||||
* HTTP 423 Locked 응답으로 매핑되며, 프론트엔드 토스트는 다국어 키
|
||||
* `auth.account_locked` 로 잔여 분(`minutes` 플레이스홀더)을 노출합니다.
|
||||
*
|
||||
* `login_lockout_time = 0`(무한대) 으로 잠긴 계정은 해제 시각이 없으므로
|
||||
* `lockedUntil` / `remainingMinutes` 가 모두 null 입니다. 이 경우 프론트엔드는
|
||||
* 잔여 시간 대신 `auth.account_locked_permanently` 안내를 노출합니다.
|
||||
*
|
||||
* 컨트롤러는 본 예외를 별도로 catch 하여 ResponseHelper 응답을 만들거나,
|
||||
* 글로벌 예외 핸들러가 자동으로 423 JSON 응답으로 변환합니다.
|
||||
*
|
||||
@@ -20,15 +24,26 @@ use Symfony\Component\HttpKernel\Exception\HttpException;
|
||||
class AccountLockedException extends HttpException
|
||||
{
|
||||
public function __construct(
|
||||
public readonly Carbon $lockedUntil,
|
||||
public readonly int $remainingMinutes,
|
||||
public readonly ?Carbon $lockedUntil,
|
||||
public readonly ?int $remainingMinutes,
|
||||
?string $message = null,
|
||||
) {
|
||||
parent::__construct(
|
||||
423,
|
||||
$message ?? 'auth.account_locked',
|
||||
$message ?? ($lockedUntil === null ? 'auth.account_locked_permanently' : 'auth.account_locked'),
|
||||
null,
|
||||
['Retry-After' => max(1, $remainingMinutes * 60)]
|
||||
// 영구 잠금은 재시도 시점을 제시할 수 없으므로 Retry-After 를 붙이지 않는다.
|
||||
$remainingMinutes === null ? [] : ['Retry-After' => max(1, $remainingMinutes * 60)]
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 영구 잠금 여부를 반환합니다.
|
||||
*
|
||||
* @return bool 해제 시각이 없는 무기한 잠금이면 true
|
||||
*/
|
||||
public function isPermanent(): bool
|
||||
{
|
||||
return $this->lockedUntil === null;
|
||||
}
|
||||
}
|
||||
@@ -29,6 +29,15 @@ use Illuminate\Support\Str;
|
||||
*/
|
||||
class MailIdentityProvider implements IdentityVerificationInterface
|
||||
{
|
||||
/** @var int 인증코드 최소 길이 */
|
||||
public const MIN_CODE_LENGTH = 4;
|
||||
|
||||
/** @var int 인증코드 최대 길이 */
|
||||
public const MAX_CODE_LENGTH = 10;
|
||||
|
||||
/** @var int 인증코드 기본 길이 (경계 위반 시 폴백) */
|
||||
public const DEFAULT_CODE_LENGTH = 6;
|
||||
|
||||
public const ID = 'g7:core.mail';
|
||||
|
||||
/**
|
||||
@@ -314,7 +323,11 @@ class MailIdentityProvider implements IdentityVerificationInterface
|
||||
'code_length' => [
|
||||
'label' => __('identity.providers.mail.settings.code_length'),
|
||||
'type' => 'integer',
|
||||
'default' => 6,
|
||||
'default' => self::DEFAULT_CODE_LENGTH,
|
||||
// 경계는 스키마가 선언한다 — 서비스가 자체 상수로 조용히 클램프하면
|
||||
// 관리자가 설정한 값이 화면 안내와 다르게 동작한다.
|
||||
'min' => self::MIN_CODE_LENGTH,
|
||||
'max' => self::MAX_CODE_LENGTH,
|
||||
'help' => __('identity.providers.mail.settings.code_length_help'),
|
||||
],
|
||||
'from_address' => [
|
||||
@@ -345,9 +358,30 @@ class MailIdentityProvider implements IdentityVerificationInterface
|
||||
return $purpose === 'password_reset' ? 'link' : 'text_code';
|
||||
}
|
||||
|
||||
/**
|
||||
* 지정 길이의 숫자 인증코드를 생성합니다.
|
||||
*
|
||||
* 경계를 벗어난 값은 조용히 클램프하지 않습니다 — 클램프는 관리자가 설정한 값과
|
||||
* 실제 동작을 어긋나게 만듭니다. 다만 런타임 인증 흐름을 중단시키는 것은 위험하므로
|
||||
* 예외 대신 경고 로그 + 스키마 기본값 폴백으로 처리합니다.
|
||||
*
|
||||
* @param int $length 요청 코드 길이
|
||||
* @return string 생성된 숫자 코드
|
||||
*/
|
||||
protected function generateNumericCode(int $length): string
|
||||
{
|
||||
$length = max(4, min(10, $length));
|
||||
if ($length < self::MIN_CODE_LENGTH || $length > self::MAX_CODE_LENGTH) {
|
||||
Log::warning('IDV 인증코드 길이가 허용 범위를 벗어나 기본값으로 대체됨', [
|
||||
'provider_id' => self::ID,
|
||||
'requested' => $length,
|
||||
'min' => self::MIN_CODE_LENGTH,
|
||||
'max' => self::MAX_CODE_LENGTH,
|
||||
'applied' => self::DEFAULT_CODE_LENGTH,
|
||||
]);
|
||||
|
||||
$length = self::DEFAULT_CODE_LENGTH;
|
||||
}
|
||||
|
||||
$code = '';
|
||||
for ($i = 0; $i < $length; $i++) {
|
||||
$code .= (string) random_int(0, 9);
|
||||
|
||||
@@ -30,6 +30,7 @@ use App\Extension\Helpers\GithubHelper;
|
||||
use App\Extension\Helpers\IdentityMessageSyncHelper;
|
||||
use App\Extension\Helpers\IdentityPolicySyncHelper;
|
||||
use App\Extension\Helpers\NotificationSyncHelper;
|
||||
use App\Extension\Testing\ExtensionTestAllowlist;
|
||||
use App\Extension\Vendor\Exceptions\VendorInstallException;
|
||||
use App\Extension\Vendor\VendorInstallContext;
|
||||
use App\Extension\Vendor\VendorInstallResult;
|
||||
@@ -2993,6 +2994,13 @@ class ModuleManager implements ModuleManagerInterface
|
||||
return;
|
||||
}
|
||||
|
||||
// 테스트 allowlist 확인 — allowlist 밖 모듈은 ServiceProvider 가 등록되지 않으므로
|
||||
// 리스너만 등록하면 훅 발화 시 Repository 바인딩이 없어 컨테이너 해석이 실패한다.
|
||||
// (모듈 등록 행은 테스트 프로세스 간 DB 에 남을 수 있어 활성 판정만으로는 부족하다)
|
||||
if (ExtensionTestAllowlist::isActive() && ! ExtensionTestAllowlist::isAllowed('module', $module->getIdentifier())) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 모듈 활성화 상태 확인 (비활성화된 모듈의 훅은 등록하지 않음)
|
||||
$activeIdentifiers = self::getActiveModuleIdentifiers();
|
||||
if (! in_array($module->getIdentifier(), $activeIdentifiers, true)) {
|
||||
@@ -4546,6 +4554,11 @@ class ModuleManager implements ModuleManagerInterface
|
||||
'updated_at' => now(),
|
||||
]);
|
||||
|
||||
// 상태 캐시 무효화 (성공 경로와 동일) — updating 창에서 누군가 활성 목록을 읽었다면
|
||||
// 그 목록에는 이 모듈이 빠져 있다. 여기서 비우지 않으면 상태를 되돌려 놓고도
|
||||
// 캐시 TTL(기본 하루) 동안 이 모듈의 화면이 계속 404 로 남는다.
|
||||
self::invalidateModuleStatusCache();
|
||||
|
||||
throw new \RuntimeException(
|
||||
__('modules.errors.update_failed', [
|
||||
'module' => $identifier,
|
||||
|
||||
@@ -29,6 +29,7 @@ use App\Extension\Helpers\GithubHelper;
|
||||
use App\Extension\Helpers\IdentityMessageSyncHelper;
|
||||
use App\Extension\Helpers\IdentityPolicySyncHelper;
|
||||
use App\Extension\Helpers\NotificationSyncHelper;
|
||||
use App\Extension\Testing\ExtensionTestAllowlist;
|
||||
use App\Extension\Vendor\Exceptions\VendorInstallException;
|
||||
use App\Extension\Vendor\VendorInstallContext;
|
||||
use App\Extension\Vendor\VendorInstallResult;
|
||||
@@ -2828,6 +2829,13 @@ class PluginManager implements PluginManagerInterface
|
||||
|
||||
protected function registerPluginHookListeners(PluginInterface $plugin): void
|
||||
{
|
||||
// 테스트 allowlist 확인 — allowlist 밖 플러그인은 ServiceProvider 가 등록되지 않으므로
|
||||
// 리스너만 등록하면 훅 발화 시 의존 바인딩이 없어 컨테이너 해석이 실패한다.
|
||||
// (플러그인 등록 행은 테스트 프로세스 간 DB 에 남을 수 있어 활성 판정만으로는 부족하다)
|
||||
if (ExtensionTestAllowlist::isActive() && ! ExtensionTestAllowlist::isAllowed('plugin', $plugin->getIdentifier())) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 플러그인 활성화 상태 확인 (비활성화된 플러그인의 훅은 등록하지 않음)
|
||||
$activeIdentifiers = self::getActivePluginIdentifiers();
|
||||
if (! in_array($plugin->getIdentifier(), $activeIdentifiers, true)) {
|
||||
@@ -4726,6 +4734,11 @@ class PluginManager implements PluginManagerInterface
|
||||
'updated_at' => now(),
|
||||
]);
|
||||
|
||||
// 상태 캐시 무효화 (성공 경로와 동일) — updating 창에서 누군가 활성 목록을 읽었다면
|
||||
// 그 목록에는 이 플러그인이 빠져 있다. 여기서 비우지 않으면 상태를 되돌려 놓고도
|
||||
// 캐시 TTL(기본 하루) 동안 이 플러그인의 화면이 계속 404 로 남는다.
|
||||
self::invalidatePluginStatusCache();
|
||||
|
||||
throw new \RuntimeException(
|
||||
__('plugins.errors.update_failed', [
|
||||
'plugin' => $identifier,
|
||||
|
||||
@@ -2,6 +2,9 @@
|
||||
|
||||
namespace App\Extension\Testing;
|
||||
|
||||
use App\Extension\HookListenerRegistrar;
|
||||
use App\Extension\HookManager;
|
||||
|
||||
/**
|
||||
* 테스트 환경 확장 로딩 allowlist
|
||||
*
|
||||
@@ -50,6 +53,8 @@ class ExtensionTestAllowlist
|
||||
*/
|
||||
public static function set(array $extensions): void
|
||||
{
|
||||
$previous = self::signature();
|
||||
|
||||
self::$plugins = [];
|
||||
self::$modules = [];
|
||||
self::$configured = true;
|
||||
@@ -63,6 +68,27 @@ class ExtensionTestAllowlist
|
||||
self::$modules[] = basename($extension);
|
||||
}
|
||||
}
|
||||
|
||||
if (self::signature() !== $previous) {
|
||||
self::forgetRegisteredHooks();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* allowlist 가 바뀌었을 때 남아 있는 훅 등록을 비웁니다.
|
||||
*
|
||||
* `HookManager` 의 훅/필터 맵과 `HookListenerRegistrar` 의 등록 이력은 static 이라
|
||||
* 테스트 클래스가 바뀌어도 프로세스에 그대로 남습니다. 앞 클래스가 허용했던 확장의
|
||||
* 리스너가 남아 있으면, 그 확장을 배선하지 않은 다음 클래스의 앱에서 훅이 발화할 때
|
||||
* `app($listenerClass)` 해석이 실패합니다 (Filter 훅은 동기 실행이라 그대로 500 이 된다).
|
||||
*
|
||||
* 비운 직후 새 앱이 부팅되며 코어·허용 확장 리스너를 다시 등록하므로, 이 초기화는
|
||||
* "이번 allowlist 에 맞는 등록만 남긴다" 는 의미가 됩니다.
|
||||
*/
|
||||
private static function forgetRegisteredHooks(): void
|
||||
{
|
||||
HookManager::resetAll();
|
||||
HookListenerRegistrar::clear();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -77,6 +103,25 @@ class ExtensionTestAllowlist
|
||||
self::$configured = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 현재 allowlist 를 비교 가능한 문자열로 반환합니다.
|
||||
*
|
||||
* @return string allowlist 서명 (미설정이면 빈 문자열)
|
||||
*/
|
||||
private static function signature(): string
|
||||
{
|
||||
if (! self::$configured) {
|
||||
return '';
|
||||
}
|
||||
|
||||
$modules = self::$modules;
|
||||
$plugins = self::$plugins;
|
||||
sort($modules);
|
||||
sort($plugins);
|
||||
|
||||
return 'm:'.implode(',', $modules).'|p:'.implode(',', $plugins);
|
||||
}
|
||||
|
||||
/**
|
||||
* 가드 활성 여부를 반환합니다.
|
||||
*
|
||||
|
||||
@@ -29,16 +29,49 @@ trait CachesModuleStatus
|
||||
return [];
|
||||
}
|
||||
|
||||
return self::resolveStatusCache()->remember(
|
||||
return self::rememberNonEmpty(
|
||||
'ext.modules.active_identifiers',
|
||||
fn () => Module::where('status', ExtensionStatus::Active->value)
|
||||
->pluck('identifier')
|
||||
->toArray(),
|
||||
(int) g7_core_settings('cache.extension_status_ttl', 86400),
|
||||
['ext.status', 'ext.modules']
|
||||
->toArray()
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 목록 캐시를 조회하되, 빈 결과는 캐시에 남기지 않습니다.
|
||||
*
|
||||
* 확장 상태는 install/activate/update 도중 잠시 active 가 아닌 값으로 바뀐다. 그 창에서
|
||||
* 누가 이 목록을 읽으면 빈 배열이 TTL(기본 하루) 동안 굳어, 작업이 끝난 뒤에도 모든 확장이
|
||||
* 꺼진 것처럼 동작한다 — 관리자 화면이 통째로 404 가 되고 스스로 회복되지 않는다.
|
||||
* 빈 결과는 재계산 비용이 사실상 없는 단순 조회이므로 캐시하지 않는 편이 안전하다.
|
||||
*
|
||||
* @param string $key 캐시 키
|
||||
* @param \Closure $resolver 목록 계산 클로저
|
||||
* @return array<string> 조회된 identifier 배열
|
||||
*/
|
||||
private static function rememberNonEmpty(string $key, \Closure $resolver): array
|
||||
{
|
||||
$cache = self::resolveStatusCache();
|
||||
$cached = $cache->get($key);
|
||||
|
||||
if (is_array($cached) && $cached !== []) {
|
||||
return $cached;
|
||||
}
|
||||
|
||||
$fresh = $resolver();
|
||||
|
||||
if ($fresh !== []) {
|
||||
$cache->put(
|
||||
$key,
|
||||
$fresh,
|
||||
(int) g7_core_settings('cache.extension_status_ttl', 86400),
|
||||
['ext.status', 'ext.modules']
|
||||
);
|
||||
}
|
||||
|
||||
return $fresh;
|
||||
}
|
||||
|
||||
/**
|
||||
* 설치된 모듈 (active + inactive) identifier 목록을 조회합니다.
|
||||
*
|
||||
@@ -50,14 +83,12 @@ trait CachesModuleStatus
|
||||
return [];
|
||||
}
|
||||
|
||||
return self::resolveStatusCache()->remember(
|
||||
return self::rememberNonEmpty(
|
||||
'ext.modules.installed_identifiers',
|
||||
fn () => Module::whereIn('status', [
|
||||
ExtensionStatus::Active->value,
|
||||
ExtensionStatus::Inactive->value,
|
||||
])->pluck('identifier')->toArray(),
|
||||
(int) g7_core_settings('cache.extension_status_ttl', 86400),
|
||||
['ext.status', 'ext.modules']
|
||||
])->pluck('identifier')->toArray()
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -29,16 +29,49 @@ trait CachesPluginStatus
|
||||
return [];
|
||||
}
|
||||
|
||||
return self::resolvePluginStatusCache()->remember(
|
||||
return self::rememberNonEmptyPluginList(
|
||||
'ext.plugins.active_identifiers',
|
||||
fn () => Plugin::where('status', ExtensionStatus::Active->value)
|
||||
->pluck('identifier')
|
||||
->toArray(),
|
||||
(int) g7_core_settings('cache.extension_status_ttl', 86400),
|
||||
['ext.status', 'ext.plugins']
|
||||
->toArray()
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 목록 캐시를 조회하되, 빈 결과는 캐시에 남기지 않습니다.
|
||||
*
|
||||
* 확장 상태는 install/activate/update 도중 잠시 active 가 아닌 값으로 바뀐다. 그 창에서
|
||||
* 누가 이 목록을 읽으면 빈 배열이 TTL(기본 하루) 동안 굳어, 작업이 끝난 뒤에도 모든
|
||||
* 플러그인이 꺼진 것처럼 동작하며 스스로 회복되지 않는다. 빈 결과는 재계산 비용이 사실상
|
||||
* 없는 단순 조회이므로 캐시하지 않는 편이 안전하다.
|
||||
*
|
||||
* @param string $key 캐시 키
|
||||
* @param \Closure $resolver 목록 계산 클로저
|
||||
* @return array<string> 조회된 identifier 배열
|
||||
*/
|
||||
private static function rememberNonEmptyPluginList(string $key, \Closure $resolver): array
|
||||
{
|
||||
$cache = self::resolvePluginStatusCache();
|
||||
$cached = $cache->get($key);
|
||||
|
||||
if (is_array($cached) && $cached !== []) {
|
||||
return $cached;
|
||||
}
|
||||
|
||||
$fresh = $resolver();
|
||||
|
||||
if ($fresh !== []) {
|
||||
$cache->put(
|
||||
$key,
|
||||
$fresh,
|
||||
(int) g7_core_settings('cache.extension_status_ttl', 86400),
|
||||
['ext.status', 'ext.plugins']
|
||||
);
|
||||
}
|
||||
|
||||
return $fresh;
|
||||
}
|
||||
|
||||
/**
|
||||
* 설치된 플러그인 (active + inactive) identifier 목록을 조회합니다.
|
||||
*
|
||||
@@ -50,14 +83,12 @@ trait CachesPluginStatus
|
||||
return [];
|
||||
}
|
||||
|
||||
return self::resolvePluginStatusCache()->remember(
|
||||
return self::rememberNonEmptyPluginList(
|
||||
'ext.plugins.installed_identifiers',
|
||||
fn () => Plugin::whereIn('status', [
|
||||
ExtensionStatus::Active->value,
|
||||
ExtensionStatus::Inactive->value,
|
||||
])->pluck('identifier')->toArray(),
|
||||
(int) g7_core_settings('cache.extension_status_ttl', 86400),
|
||||
['ext.status', 'ext.plugins']
|
||||
])->pluck('identifier')->toArray()
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -29,13 +29,11 @@ trait CachesTemplateStatus
|
||||
return [];
|
||||
}
|
||||
|
||||
return self::resolveTemplateStatusCache()->remember(
|
||||
return self::rememberNonEmptyTemplateList(
|
||||
'ext.templates.active_identifiers',
|
||||
fn () => Template::where('status', ExtensionStatus::Active->value)
|
||||
->pluck('identifier')
|
||||
->toArray(),
|
||||
(int) g7_core_settings('cache.extension_status_ttl', 86400),
|
||||
['ext.status', 'ext.templates']
|
||||
->toArray()
|
||||
);
|
||||
}
|
||||
|
||||
@@ -51,14 +49,12 @@ trait CachesTemplateStatus
|
||||
return [];
|
||||
}
|
||||
|
||||
return self::resolveTemplateStatusCache()->remember(
|
||||
return self::rememberNonEmptyTemplateList(
|
||||
"ext.templates.active_identifiers_{$type}",
|
||||
fn () => Template::where('status', ExtensionStatus::Active->value)
|
||||
->where('type', $type)
|
||||
->pluck('identifier')
|
||||
->toArray(),
|
||||
(int) g7_core_settings('cache.extension_status_ttl', 86400),
|
||||
['ext.status', 'ext.templates']
|
||||
->toArray()
|
||||
);
|
||||
}
|
||||
|
||||
@@ -73,17 +69,50 @@ trait CachesTemplateStatus
|
||||
return [];
|
||||
}
|
||||
|
||||
return self::resolveTemplateStatusCache()->remember(
|
||||
return self::rememberNonEmptyTemplateList(
|
||||
'ext.templates.installed_identifiers',
|
||||
fn () => Template::whereIn('status', [
|
||||
ExtensionStatus::Active->value,
|
||||
ExtensionStatus::Inactive->value,
|
||||
])->pluck('identifier')->toArray(),
|
||||
(int) g7_core_settings('cache.extension_status_ttl', 86400),
|
||||
['ext.status', 'ext.templates']
|
||||
])->pluck('identifier')->toArray()
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 목록 캐시를 조회하되, 빈 결과는 캐시에 남기지 않습니다.
|
||||
*
|
||||
* 확장 상태는 install/activate/update 도중 잠시 active 가 아닌 값으로 바뀐다. 그 창에서
|
||||
* 누가 이 목록을 읽으면 빈 배열이 TTL(기본 하루) 동안 굳어, 작업이 끝난 뒤에도 모든
|
||||
* 템플릿이 꺼진 것처럼 동작하며 스스로 회복되지 않는다. 빈 결과는 재계산 비용이 사실상
|
||||
* 없는 단순 조회이므로 캐시하지 않는 편이 안전하다.
|
||||
*
|
||||
* @param string $key 캐시 키
|
||||
* @param \Closure $resolver 목록 계산 클로저
|
||||
* @return array<string> 조회된 identifier 배열
|
||||
*/
|
||||
private static function rememberNonEmptyTemplateList(string $key, \Closure $resolver): array
|
||||
{
|
||||
$cache = self::resolveTemplateStatusCache();
|
||||
$cached = $cache->get($key);
|
||||
|
||||
if (is_array($cached) && $cached !== []) {
|
||||
return $cached;
|
||||
}
|
||||
|
||||
$fresh = $resolver();
|
||||
|
||||
if ($fresh !== []) {
|
||||
$cache->put(
|
||||
$key,
|
||||
$fresh,
|
||||
(int) g7_core_settings('cache.extension_status_ttl', 86400),
|
||||
['ext.status', 'ext.templates']
|
||||
);
|
||||
}
|
||||
|
||||
return $fresh;
|
||||
}
|
||||
|
||||
/**
|
||||
* 템플릿 상태 캐시를 무효화합니다.
|
||||
* 템플릿 상태 변경 시 (install, activate, deactivate, uninstall) 호출해야 합니다.
|
||||
|
||||
@@ -2,7 +2,6 @@
|
||||
|
||||
namespace App\Helpers;
|
||||
|
||||
use App\Enums\ScopeType;
|
||||
use App\Models\Permission;
|
||||
use App\Models\User;
|
||||
use App\Providers\AuthServiceProvider;
|
||||
@@ -26,6 +25,20 @@ class PermissionHelper
|
||||
*/
|
||||
protected static array $permissionCache = [];
|
||||
|
||||
/**
|
||||
* 권한 스코프 캐시를 무효화합니다.
|
||||
*
|
||||
* 캐시는 프로세스 수명 동안 유지되므로, 권한 행이 다시 만들어지는 시점
|
||||
* (권한 재시드 · 코어 업데이트 · 확장 install) 에 비워 주어야 한다.
|
||||
* 테스트에서는 매 케이스마다 DB 가 초기화되는데 캐시만 남아, 앞 케이스가 심은
|
||||
* `resource_route_key = null` 이 뒤 케이스로 새어 스코프 검사가 통째로 건너뛰어진다
|
||||
* (개별 실행은 통과하고 스위트에서만 어긋나는 형태로 드러난다).
|
||||
*/
|
||||
public static function clearPermissionScopeCache(): void
|
||||
{
|
||||
self::$permissionCache = [];
|
||||
}
|
||||
|
||||
/**
|
||||
* 단일 권한 체크
|
||||
*
|
||||
@@ -104,7 +117,6 @@ class PermissionHelper
|
||||
* @param Builder $query Eloquent 쿼리 빌더
|
||||
* @param string $permission 권한 식별자
|
||||
* @param User|null $user 사용자 (null이면 현재 인증 사용자)
|
||||
* @return void
|
||||
*/
|
||||
public static function applyPermissionScope(Builder $query, string $permission, ?User $user = null): void
|
||||
{
|
||||
|
||||
@@ -4,11 +4,11 @@ namespace App\Http\Controllers\Api\Admin;
|
||||
|
||||
use App\Exceptions\Auth\AccountLockedException;
|
||||
use App\Http\Controllers\Api\Base\AdminBaseController;
|
||||
use App\Http\Requests\Auth\AuthenticatedRequest;
|
||||
use App\Http\Requests\Auth\LoginRequest;
|
||||
use App\Http\Resources\UserResource;
|
||||
use App\Services\AuthService;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
class AuthController extends AdminBaseController
|
||||
@@ -22,7 +22,7 @@ class AuthController extends AdminBaseController
|
||||
/**
|
||||
* 관리자를 로그인시킵니다.
|
||||
*
|
||||
* @param LoginRequest $request 로그인 요청 데이터
|
||||
* @param LoginRequest $request 로그인 요청 데이터
|
||||
* @return JsonResponse 로그인 결과와 관리자 정보, 토큰을 포함한 JSON 응답
|
||||
*/
|
||||
public function login(LoginRequest $request): JsonResponse
|
||||
@@ -36,7 +36,7 @@ class AuthController extends AdminBaseController
|
||||
$user = $data['user'];
|
||||
|
||||
// 관리자 권한 확인
|
||||
if (!$user->isAdmin()) {
|
||||
if (! $user->isAdmin()) {
|
||||
return $this->forbidden('auth.admin_required');
|
||||
}
|
||||
|
||||
@@ -45,10 +45,17 @@ class AuthController extends AdminBaseController
|
||||
|
||||
return $this->success('auth.admin_login_success', $data);
|
||||
} catch (AccountLockedException $e) {
|
||||
return $this->error('auth.account_locked', 423, [
|
||||
'locked_until' => $e->lockedUntil->toIso8601String(),
|
||||
'retry_after_seconds' => $e->remainingMinutes * 60,
|
||||
], ['minutes' => $e->remainingMinutes]);
|
||||
// 영구 잠금(무한대 설정)은 해제 시각·잔여 시간이 없다 — null 그대로 노출.
|
||||
return $this->error(
|
||||
$e->isPermanent() ? 'auth.account_locked_permanently' : 'auth.account_locked',
|
||||
423,
|
||||
[
|
||||
'locked_until' => $e->lockedUntil?->toIso8601String(),
|
||||
'retry_after_seconds' => $e->remainingMinutes === null ? null : $e->remainingMinutes * 60,
|
||||
'permanent' => $e->isPermanent(),
|
||||
],
|
||||
['minutes' => $e->remainingMinutes]
|
||||
);
|
||||
} catch (ValidationException $e) {
|
||||
return $this->unauthorized('auth.login_failed');
|
||||
}
|
||||
@@ -57,10 +64,10 @@ class AuthController extends AdminBaseController
|
||||
/**
|
||||
* 관리자를 로그아웃시킵니다.
|
||||
*
|
||||
* @param Request $request HTTP 요청
|
||||
* @param AuthenticatedRequest $request 인증 세션 요청 (본문 입력 없음)
|
||||
* @return JsonResponse 로그아웃 성공 메시지
|
||||
*/
|
||||
public function logout(Request $request): JsonResponse
|
||||
public function logout(AuthenticatedRequest $request): JsonResponse
|
||||
{
|
||||
$this->authService->logout($request->user());
|
||||
|
||||
@@ -70,10 +77,10 @@ class AuthController extends AdminBaseController
|
||||
/**
|
||||
* 현재 로그인된 관리자의 정보를 반환합니다.
|
||||
*
|
||||
* @param Request $request HTTP 요청
|
||||
* @param AuthenticatedRequest $request 인증 세션 요청 (본문 입력 없음)
|
||||
* @return JsonResponse 관리자 정보를 포함한 JSON 응답
|
||||
*/
|
||||
public function user(Request $request): JsonResponse
|
||||
public function user(AuthenticatedRequest $request): JsonResponse
|
||||
{
|
||||
$user = $request->user();
|
||||
|
||||
@@ -89,10 +96,10 @@ class AuthController extends AdminBaseController
|
||||
/**
|
||||
* 관리자의 인증 토큰을 갱신합니다.
|
||||
*
|
||||
* @param Request $request HTTP 요청
|
||||
* @param AuthenticatedRequest $request 인증 세션 요청 (본문 입력 없음)
|
||||
* @return JsonResponse 새로운 토큰과 관리자 정보를 포함한 JSON 응답
|
||||
*/
|
||||
public function refresh(Request $request): JsonResponse
|
||||
public function refresh(AuthenticatedRequest $request): JsonResponse
|
||||
{
|
||||
try {
|
||||
$data = $this->authService->refreshToken($request->user());
|
||||
@@ -101,6 +108,7 @@ class AuthController extends AdminBaseController
|
||||
if (isset($data['user'])) {
|
||||
$data['user'] = new UserResource($data['user']);
|
||||
}
|
||||
|
||||
return $this->success('common.success', $data);
|
||||
} catch (ValidationException $e) {
|
||||
return $this->unauthorized('auth.unauthenticated');
|
||||
|
||||
@@ -42,6 +42,7 @@ class SettingsController extends AdminBaseController
|
||||
try {
|
||||
$settings = $this->settingsService->getAllSettings();
|
||||
$settings['available_drivers'] = $this->driverRegistryService->getAllAvailableDrivers();
|
||||
$settings['_meta'] = ['limits' => config('core.settings_limits', [])];
|
||||
|
||||
return $this->success('settings.fetch_success',
|
||||
(new SettingsResource($settings))->toArray(request())
|
||||
@@ -69,6 +70,7 @@ class SettingsController extends AdminBaseController
|
||||
// 저장 후 전체 설정 반환 (관리자 UI 상태 업데이트용)
|
||||
$allSettings = $this->settingsService->getAllSettings();
|
||||
$allSettings['available_drivers'] = $this->driverRegistryService->getAllAvailableDrivers();
|
||||
$allSettings['_meta'] = ['limits' => config('core.settings_limits', [])];
|
||||
|
||||
return $this->success('settings.save_success', [
|
||||
'settings' => $allSettings,
|
||||
|
||||
@@ -129,6 +129,30 @@ class UserController extends AdminBaseController
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 사용자의 계정 잠금을 해제합니다.
|
||||
*
|
||||
* 로그인 실패 누적으로 잠긴 계정(특히 잠금 시간 0 = 무한대 설정으로 영구 잠긴 계정)을
|
||||
* 관리자가 수동으로 풀어 줍니다. 이 경로가 없으면 영구 잠금 계정은 성공 로그인 자체가
|
||||
* 불가하므로 복구 수단이 없습니다.
|
||||
*
|
||||
* @param User $user 잠금을 해제할 사용자 모델
|
||||
* @return JsonResponse 갱신된 사용자 정보를 포함한 JSON 응답
|
||||
*/
|
||||
public function unlock(User $user): JsonResponse
|
||||
{
|
||||
try {
|
||||
$unlocked = $this->userService->unlockAccount($user);
|
||||
|
||||
return $this->successWithResource(
|
||||
'auth.account_unlocked',
|
||||
new UserResource($unlocked)
|
||||
);
|
||||
} catch (Exception $e) {
|
||||
return $this->error('user.update_failed', 500, $e, ['error' => $e->getMessage()]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 사용자를 삭제합니다.
|
||||
*
|
||||
|
||||
@@ -4,6 +4,7 @@ namespace App\Http\Controllers\Api\Auth;
|
||||
|
||||
use App\Exceptions\Auth\AccountLockedException;
|
||||
use App\Http\Controllers\Api\Base\AuthBaseController;
|
||||
use App\Http\Requests\Auth\AuthenticatedRequest;
|
||||
use App\Http\Requests\Auth\ForgotPasswordRequest;
|
||||
use App\Http\Requests\Auth\LoginRequest;
|
||||
use App\Http\Requests\Auth\RegisterRequest;
|
||||
@@ -12,7 +13,6 @@ use App\Http\Requests\Auth\ValidateResetTokenRequest;
|
||||
use App\Http\Resources\UserResource;
|
||||
use App\Services\AuthService;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
class AuthController extends AuthBaseController
|
||||
@@ -52,10 +52,17 @@ class AuthController extends AuthBaseController
|
||||
|
||||
return $this->success('auth.login_success', $data);
|
||||
} catch (AccountLockedException $e) {
|
||||
return $this->error('auth.account_locked', 423, [
|
||||
'locked_until' => $e->lockedUntil->toIso8601String(),
|
||||
'retry_after_seconds' => $e->remainingMinutes * 60,
|
||||
], ['minutes' => $e->remainingMinutes]);
|
||||
// 영구 잠금(무한대 설정)은 해제 시각·잔여 시간이 없다 — null 그대로 노출.
|
||||
return $this->error(
|
||||
$e->isPermanent() ? 'auth.account_locked_permanently' : 'auth.account_locked',
|
||||
423,
|
||||
[
|
||||
'locked_until' => $e->lockedUntil?->toIso8601String(),
|
||||
'retry_after_seconds' => $e->remainingMinutes === null ? null : $e->remainingMinutes * 60,
|
||||
'permanent' => $e->isPermanent(),
|
||||
],
|
||||
['minutes' => $e->remainingMinutes]
|
||||
);
|
||||
} catch (ValidationException $e) {
|
||||
return $this->unauthorized('auth.login_failed');
|
||||
}
|
||||
@@ -84,10 +91,10 @@ class AuthController extends AuthBaseController
|
||||
/**
|
||||
* 사용자를 로그아웃시킵니다. (현재 디바이스만)
|
||||
*
|
||||
* @param Request $request HTTP 요청
|
||||
* @param AuthenticatedRequest $request 인증 세션 요청 (본문 입력 없음)
|
||||
* @return JsonResponse 로그아웃 성공 메시지
|
||||
*/
|
||||
public function logout(Request $request): JsonResponse
|
||||
public function logout(AuthenticatedRequest $request): JsonResponse
|
||||
{
|
||||
$this->authService->logout($request->user());
|
||||
|
||||
@@ -97,10 +104,10 @@ class AuthController extends AuthBaseController
|
||||
/**
|
||||
* 모든 디바이스에서 사용자를 로그아웃시킵니다.
|
||||
*
|
||||
* @param Request $request HTTP 요청
|
||||
* @param AuthenticatedRequest $request 인증 세션 요청 (본문 입력 없음)
|
||||
* @return JsonResponse 로그아웃 성공 메시지
|
||||
*/
|
||||
public function logoutFromAllDevices(Request $request): JsonResponse
|
||||
public function logoutFromAllDevices(AuthenticatedRequest $request): JsonResponse
|
||||
{
|
||||
$this->authService->logoutFromAllDevices($request->user());
|
||||
|
||||
@@ -110,10 +117,10 @@ class AuthController extends AuthBaseController
|
||||
/**
|
||||
* 현재 로그인된 사용자의 정보를 반환합니다.
|
||||
*
|
||||
* @param Request $request HTTP 요청
|
||||
* @param AuthenticatedRequest $request 인증 세션 요청 (본문 입력 없음)
|
||||
* @return JsonResponse 사용자 정보를 포함한 JSON 응답
|
||||
*/
|
||||
public function user(Request $request): JsonResponse
|
||||
public function user(AuthenticatedRequest $request): JsonResponse
|
||||
{
|
||||
$user = $request->user();
|
||||
|
||||
@@ -131,10 +138,10 @@ class AuthController extends AuthBaseController
|
||||
/**
|
||||
* 사용자의 인증 토큰을 갱신합니다.
|
||||
*
|
||||
* @param Request $request HTTP 요청
|
||||
* @param AuthenticatedRequest $request 인증 세션 요청 (본문 입력 없음)
|
||||
* @return JsonResponse 새로운 토큰과 사용자 정보를 포함한 JSON 응답
|
||||
*/
|
||||
public function refresh(Request $request): JsonResponse
|
||||
public function refresh(AuthenticatedRequest $request): JsonResponse
|
||||
{
|
||||
$data = $this->authService->refreshToken($request->user());
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace App\Http\Controllers\Api\Public;
|
||||
|
||||
use App\Contracts\Extension\CacheInterface;
|
||||
use App\Enums\ExtensionStatus;
|
||||
use App\Extension\Helpers\EditorSpecAssembler;
|
||||
use App\Extension\Traits\ClearsTemplateCaches;
|
||||
@@ -12,6 +13,7 @@ use App\Services\TemplateLayoutAttachmentService;
|
||||
use App\Services\TemplateService;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Response;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Symfony\Component\HttpFoundation\BinaryFileResponse;
|
||||
|
||||
/**
|
||||
@@ -40,22 +42,36 @@ class PublicTemplateController extends PublicBaseController
|
||||
// 캐시 버전을 키에 포함하여 모듈/플러그인 변경 시 캐시 무효화
|
||||
$cacheVersion = request()->query('v', 0);
|
||||
|
||||
// 캐싱된 응답 반환 (1시간 유효)
|
||||
$routesData = $this->cached(
|
||||
"template.routes.{$identifier}.v{$cacheVersion}",
|
||||
function () use ($identifier) {
|
||||
// Service에서 템플릿 + 모듈 routes 데이터 병합 조회
|
||||
$result = $this->templateService->getRoutesDataWithModules($identifier);
|
||||
// 확장 업데이트 중에는 활성 디렉토리가 잠시 비어 그 모듈의 라우트가 통째로 빠진다.
|
||||
// 그 순간의 응답을 버전 키에 캐시하면 업데이트가 끝난 뒤에도 캐시가 만료될 때까지
|
||||
// 해당 모듈의 모든 화면이 404 로 남는다 — 버전은 이미 올라간 뒤라 스스로 회복되지 않는다.
|
||||
// 따라서 열화 스냅샷은 그대로 응답하되 캐시에 남기지 않는다.
|
||||
$buildRoutes = function () use ($identifier) {
|
||||
$result = $this->templateService->getRoutesDataWithModules($identifier);
|
||||
|
||||
// 에러 처리
|
||||
if (! $result['success']) {
|
||||
return ['error' => $result['error']];
|
||||
}
|
||||
if (! $result['success']) {
|
||||
return ['error' => $result['error']];
|
||||
}
|
||||
|
||||
return ['success' => true, 'data' => $result['data']];
|
||||
},
|
||||
3600
|
||||
);
|
||||
return ['success' => true, 'data' => $result['data']];
|
||||
};
|
||||
|
||||
$cacheKey = "template.routes.{$identifier}.v{$cacheVersion}";
|
||||
$cache = app(CacheInterface::class);
|
||||
$routesData = $cache->get($cacheKey);
|
||||
|
||||
if ($routesData === null) {
|
||||
$routesData = $buildRoutes();
|
||||
|
||||
if ($this->templateService->lastRouteMergeWasDegraded()) {
|
||||
Log::warning('라우트 병합이 열화 상태여서 캐시하지 않습니다 (확장 업데이트 진행 중 추정)', [
|
||||
'template' => $identifier,
|
||||
'cache_version' => $cacheVersion,
|
||||
]);
|
||||
} else {
|
||||
$cache->put($cacheKey, $routesData, 3600);
|
||||
}
|
||||
}
|
||||
|
||||
// 에러 응답 처리
|
||||
if (isset($routesData['error'])) {
|
||||
|
||||
@@ -29,10 +29,18 @@ class UploadAttachmentRequest extends FormRequest
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
$maxSize = config('attachment.max_size', 10) * 1024; // MB to KB
|
||||
// config/attachment.max_file_size 는 KB 단위 (관리자 설정 MB → KB 변환은 SettingsServiceProvider 담당)
|
||||
$maxSize = (int) config('attachment.max_file_size', 10240);
|
||||
$extensions = $this->allowedExtensions();
|
||||
|
||||
$fileRules = ['required', 'file', 'max:'.$maxSize];
|
||||
// 목록이 비면 확장자 제한 없음 (탈출구) — 빈 규칙을 붙이면 전 파일이 거부된다
|
||||
if ($extensions !== []) {
|
||||
$fileRules[] = 'extensions:'.implode(',', $extensions);
|
||||
}
|
||||
|
||||
$rules = [
|
||||
'file' => ['required', 'file', 'max:' . $maxSize],
|
||||
'file' => $fileRules,
|
||||
'attachmentable_type' => ['nullable', 'string', 'max:255'],
|
||||
'attachmentable_id' => ['nullable', 'integer', 'min:1'],
|
||||
'collection' => ['sometimes', 'string', 'max:100'],
|
||||
@@ -54,7 +62,8 @@ class UploadAttachmentRequest extends FormRequest
|
||||
return [
|
||||
'file.required' => __('attachment.validation.file_required'),
|
||||
'file.file' => __('attachment.validation.file_invalid'),
|
||||
'file.max' => __('attachment.validation.file_max', ['max' => config('attachment.max_size', 10)]),
|
||||
'file.max' => __('attachment.validation.file_max', ['max' => (int) config('attachment.max_file_size', 10240) / 1024]),
|
||||
'file.extensions' => __('attachment.validation.file_extension_invalid', ['extensions' => implode(', ', $this->allowedExtensions())]),
|
||||
'attachmentable_type.string' => __('attachment.validation.type_invalid'),
|
||||
'attachmentable_id.integer' => __('attachment.validation.id_invalid'),
|
||||
];
|
||||
@@ -62,8 +71,6 @@ class UploadAttachmentRequest extends FormRequest
|
||||
|
||||
/**
|
||||
* 검증 전 데이터 준비
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected function prepareForValidation(): void
|
||||
{
|
||||
@@ -72,4 +79,25 @@ class UploadAttachmentRequest extends FormRequest
|
||||
'source_type' => $this->source_type ?? AttachmentSourceType::Core->value,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 허용 확장자 목록을 반환합니다 (소문자 정규화 + 확장 훅 적용).
|
||||
*
|
||||
* 빈 배열은 "확장자 제한 없음" 을 의미합니다.
|
||||
*
|
||||
* @return array<int, string> 허용 확장자 목록
|
||||
*/
|
||||
protected function allowedExtensions(): array
|
||||
{
|
||||
$extensions = (array) config('attachment.allowed_extensions', []);
|
||||
|
||||
$extensions = array_values(array_filter(array_map(
|
||||
static fn ($ext) => strtolower(trim(ltrim((string) $ext, '.'))),
|
||||
$extensions
|
||||
)));
|
||||
|
||||
return array_values(array_unique(
|
||||
(array) HookManager::applyFilters('core.attachment.allowed_extensions', $extensions, $this)
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -29,11 +29,19 @@ class UploadBatchAttachmentRequest extends FormRequest
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
$maxSize = config('attachment.max_size', 10) * 1024; // MB to KB
|
||||
// config/attachment.max_file_size 는 KB 단위 (관리자 설정 MB → KB 변환은 SettingsServiceProvider 담당)
|
||||
$maxSize = (int) config('attachment.max_file_size', 10240);
|
||||
$extensions = $this->allowedExtensions();
|
||||
|
||||
$fileRules = ['file', 'max:'.$maxSize];
|
||||
// 목록이 비면 확장자 제한 없음 (탈출구) — 빈 규칙을 붙이면 전 파일이 거부된다
|
||||
if ($extensions !== []) {
|
||||
$fileRules[] = 'extensions:'.implode(',', $extensions);
|
||||
}
|
||||
|
||||
$rules = [
|
||||
'files' => ['required', 'array', 'min:1'],
|
||||
'files.*' => ['file', 'max:' . $maxSize],
|
||||
'files.*' => $fileRules,
|
||||
'attachmentable_type' => ['nullable', 'string', 'max:255'],
|
||||
'attachmentable_id' => ['nullable', 'integer', 'min:1'],
|
||||
'collection' => ['sometimes', 'string', 'max:100'],
|
||||
@@ -57,7 +65,8 @@ class UploadBatchAttachmentRequest extends FormRequest
|
||||
'files.array' => __('attachment.validation.files_array'),
|
||||
'files.min' => __('attachment.validation.files_min'),
|
||||
'files.*.file' => __('attachment.validation.file_invalid'),
|
||||
'files.*.max' => __('attachment.validation.file_max', ['max' => config('attachment.max_size', 10)]),
|
||||
'files.*.max' => __('attachment.validation.file_max', ['max' => (int) config('attachment.max_file_size', 10240) / 1024]),
|
||||
'files.*.extensions' => __('attachment.validation.file_extension_invalid', ['extensions' => implode(', ', $this->allowedExtensions())]),
|
||||
'attachmentable_type.string' => __('attachment.validation.type_invalid'),
|
||||
'attachmentable_id.integer' => __('attachment.validation.id_invalid'),
|
||||
];
|
||||
@@ -65,8 +74,6 @@ class UploadBatchAttachmentRequest extends FormRequest
|
||||
|
||||
/**
|
||||
* 검증 전 데이터 준비
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected function prepareForValidation(): void
|
||||
{
|
||||
@@ -75,4 +82,25 @@ class UploadBatchAttachmentRequest extends FormRequest
|
||||
'source_type' => $this->source_type ?? AttachmentSourceType::Core->value,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 허용 확장자 목록을 반환합니다 (소문자 정규화 + 확장 훅 적용).
|
||||
*
|
||||
* 빈 배열은 "확장자 제한 없음" 을 의미합니다.
|
||||
*
|
||||
* @return array<int, string> 허용 확장자 목록
|
||||
*/
|
||||
protected function allowedExtensions(): array
|
||||
{
|
||||
$extensions = (array) config('attachment.allowed_extensions', []);
|
||||
|
||||
$extensions = array_values(array_filter(array_map(
|
||||
static fn ($ext) => strtolower(trim(ltrim((string) $ext, '.'))),
|
||||
$extensions
|
||||
)));
|
||||
|
||||
return array_values(array_unique(
|
||||
(array) HookManager::applyFilters('core.attachment.allowed_extensions', $extensions, $this)
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Requests\Auth;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
|
||||
/**
|
||||
* 본문 입력이 없는 인증 세션 요청
|
||||
*
|
||||
* 로그아웃 · 현재 사용자 조회 · 토큰 갱신처럼 토큰으로 식별되는 주체만 있으면 되고
|
||||
* 본문 입력을 받지 않는 엔드포인트가 공유합니다. 검증 규칙이 비어 있다는 사실 자체가
|
||||
* "이 엔드포인트는 어떤 입력도 받지 않는다" 는 선언이며, 나중에 입력이 생기면 그 규칙을
|
||||
* 둘 자리가 이미 마련되어 있습니다.
|
||||
*
|
||||
* 인증은 라우트의 `auth:sanctum` 미들웨어가, 권한은 permission 미들웨어가 담당합니다.
|
||||
*/
|
||||
class AuthenticatedRequest extends FormRequest
|
||||
{
|
||||
/**
|
||||
* 사용자가 이 요청을 수행할 권한이 있는지 확인합니다.
|
||||
*
|
||||
* @return bool 항상 true (인증·권한은 미들웨어에서 검증)
|
||||
*/
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 검증 규칙을 반환합니다.
|
||||
*
|
||||
* @return array<string, mixed> 빈 배열 (본문 입력 없음)
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
}
|
||||
@@ -3,12 +3,15 @@
|
||||
namespace App\Http\Requests\Auth;
|
||||
|
||||
use App\Extension\HookManager;
|
||||
use Illuminate\Contracts\Validation\ValidationRule;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
|
||||
class LoginRequest extends FormRequest
|
||||
{
|
||||
/**
|
||||
* Determine if the user is authorized to make this request.
|
||||
*
|
||||
* @return bool 항상 true (권한은 미들웨어에서 검증)
|
||||
*/
|
||||
public function authorize(): bool
|
||||
{
|
||||
@@ -18,13 +21,15 @@ class LoginRequest extends FormRequest
|
||||
/**
|
||||
* Get the validation rules that apply to the request.
|
||||
*
|
||||
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
|
||||
* @return array<string, ValidationRule|array<mixed>|string>
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
$rules = [
|
||||
'email' => 'required|email',
|
||||
'password' => 'required|string|min:6',
|
||||
// 로그인은 기존 비밀번호를 대조하는 행위이지 새 정책을 강제하는 지점이 아니다.
|
||||
// 길이 규칙을 두면 정책 미달 비밀번호에 422 를 주어 미인증 공격자에게 그 사실을 누설한다.
|
||||
'password' => 'required|string',
|
||||
];
|
||||
|
||||
// 모듈/플러그인이 validation rules를 동적으로 추가할 수 있도록 훅 제공
|
||||
@@ -42,7 +47,6 @@ class LoginRequest extends FormRequest
|
||||
'email.required' => __('validation.auth.email.required'),
|
||||
'email.email' => __('validation.auth.email.email'),
|
||||
'password.required' => __('validation.auth.password.required'),
|
||||
'password.min' => __('validation.auth.password.min'),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ namespace App\Http\Requests\Auth;
|
||||
|
||||
use App\Extension\HookManager;
|
||||
use App\Models\User;
|
||||
use App\Rules\PasswordPolicy;
|
||||
use Illuminate\Contracts\Validation\ValidationRule;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Validation\Rule;
|
||||
@@ -31,7 +32,7 @@ class RegisterRequest extends FormRequest
|
||||
'name' => 'required|string|max:255',
|
||||
'nickname' => 'nullable|string|max:50',
|
||||
'email' => ['required', 'string', 'email', 'max:255', Rule::unique(User::class)],
|
||||
'password' => 'required|string|min:8|confirmed',
|
||||
'password' => ['required', 'string', 'confirmed', PasswordPolicy::rule()],
|
||||
'mobile' => ['nullable', 'string', 'max:20', 'regex:/^[0-9\-\+\(\)\s]+$/'],
|
||||
'phone' => ['nullable', 'string', 'max:20', 'regex:/^[0-9\-\+\(\)\s]+$/'],
|
||||
'language' => 'nullable|string|in:'.implode(',', config('app.supported_locales', ['ko', 'en'])),
|
||||
|
||||
@@ -4,6 +4,8 @@ namespace App\Http\Requests\Auth;
|
||||
|
||||
use App\Extension\HookManager;
|
||||
use App\Models\User;
|
||||
use App\Rules\PasswordPolicy;
|
||||
use Illuminate\Contracts\Validation\ValidationRule;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Validation\Rule;
|
||||
|
||||
@@ -11,6 +13,8 @@ class ResetPasswordRequest extends FormRequest
|
||||
{
|
||||
/**
|
||||
* Determine if the user is authorized to make this request.
|
||||
*
|
||||
* @return bool 항상 true (권한은 미들웨어에서 검증)
|
||||
*/
|
||||
public function authorize(): bool
|
||||
{
|
||||
@@ -20,14 +24,14 @@ class ResetPasswordRequest extends FormRequest
|
||||
/**
|
||||
* Get the validation rules that apply to the request.
|
||||
*
|
||||
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
|
||||
* @return array<string, ValidationRule|array<mixed>|string>
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
$rules = [
|
||||
'token' => 'required|string',
|
||||
'email' => ['required', 'email', Rule::exists(User::class, 'email')],
|
||||
'password' => 'required|string|min:8|confirmed',
|
||||
'password' => ['required', 'string', 'confirmed', PasswordPolicy::rule()],
|
||||
];
|
||||
|
||||
// 모듈/플러그인이 validation rules를 동적으로 추가할 수 있도록 훅 제공
|
||||
|
||||
@@ -5,6 +5,7 @@ namespace App\Http\Requests\Settings;
|
||||
use App\Extension\HookManager;
|
||||
use App\Models\Attachment;
|
||||
use App\Search\Engines\DatabaseFulltextEngine;
|
||||
use App\Support\AllowedExtensions;
|
||||
use App\Support\AssetUrl;
|
||||
use Illuminate\Contracts\Validation\ValidationRule;
|
||||
use Illuminate\Contracts\Validation\Validator;
|
||||
@@ -106,6 +107,28 @@ class SaveSettingsRequest extends FormRequest
|
||||
'advanced.geoip_enabled',
|
||||
'advanced.geoip_auto_update_enabled',
|
||||
]);
|
||||
|
||||
$this->normalizeAllowedExtensions();
|
||||
}
|
||||
|
||||
/**
|
||||
* 허용 확장자를 저장 형태(소문자 확장자 배열)로 정규화합니다.
|
||||
*
|
||||
* 화면 입력 칸은 콤마로 구분한 한 줄 텍스트라 이 값은 문자열로 들어온다. 문자열 그대로
|
||||
* 저장하면 업로드 제한을 적용하는 지점이 그 값을 쓰지 못해, 저장은 성공하는데 제한은
|
||||
* 종전 목록으로 남는다. 형태 판정은 저장 경로 진입 전 이 한 곳에서만 수행한다.
|
||||
*/
|
||||
private function normalizeAllowedExtensions(): void
|
||||
{
|
||||
$upload = $this->input('upload', []);
|
||||
|
||||
if (! is_array($upload) || ! array_key_exists('allowed_extensions', $upload)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$upload['allowed_extensions'] = AllowedExtensions::normalize($upload['allowed_extensions']);
|
||||
|
||||
$this->merge(['upload' => $upload]);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -202,11 +225,11 @@ class SaveSettingsRequest extends FormRequest
|
||||
'mail.from_name' => $this->getTabRules($tab, 'mail', 'string|max:255'),
|
||||
|
||||
// 업로드 설정
|
||||
'upload.max_file_size' => $this->getTabRules($tab, 'upload', 'integer|min:1|max:1024'),
|
||||
'upload.max_file_size' => $this->getTabRules($tab, 'upload', 'integer|min:'.config('core.settings_limits.upload_max_file_size_min', 1).'|max:'.config('core.settings_limits.upload_max_file_size_max', 1024)),
|
||||
'upload.allowed_extensions' => $this->getAllowedExtensionsRules($tab),
|
||||
'upload.image_max_width' => ['nullable', 'integer', 'min:100', 'max:10000'],
|
||||
'upload.image_max_height' => ['nullable', 'integer', 'min:100', 'max:10000'],
|
||||
'upload.image_quality' => ['nullable', 'integer', 'min:1', 'max:100'],
|
||||
'upload.image_max_width' => ['nullable', 'integer', 'min:'.config('core.settings_limits.upload_image_max_width_min', 100), 'max:'.config('core.settings_limits.upload_image_max_width_max', 10000)],
|
||||
'upload.image_max_height' => ['nullable', 'integer', 'min:'.config('core.settings_limits.upload_image_max_height_min', 100), 'max:'.config('core.settings_limits.upload_image_max_height_max', 10000)],
|
||||
'upload.image_quality' => ['nullable', 'integer', 'min:'.config('core.settings_limits.upload_image_quality_min', 1), 'max:'.config('core.settings_limits.upload_image_quality_max', 100)],
|
||||
|
||||
// SEO 설정
|
||||
'seo.meta_title_suffix' => ['nullable', 'string', 'max:100'],
|
||||
@@ -220,16 +243,16 @@ class SaveSettingsRequest extends FormRequest
|
||||
'seo.bot_detection_enabled' => ['nullable', 'boolean'],
|
||||
'seo.bot_detection_library_enabled' => ['nullable', 'boolean'],
|
||||
'seo.og_default_site_name' => ['nullable', 'string', 'max:200'],
|
||||
'seo.og_image_default_width' => ['nullable', 'integer', 'min:0', 'max:8000'],
|
||||
'seo.og_image_default_height' => ['nullable', 'integer', 'min:0', 'max:8000'],
|
||||
'seo.og_image_default_width' => ['nullable', 'integer', 'min:'.config('core.settings_limits.seo_og_image_default_width_min', 0), 'max:'.config('core.settings_limits.seo_og_image_default_width_max', 8000)],
|
||||
'seo.og_image_default_height' => ['nullable', 'integer', 'min:'.config('core.settings_limits.seo_og_image_default_height_min', 0), 'max:'.config('core.settings_limits.seo_og_image_default_height_max', 8000)],
|
||||
'seo.twitter_default_card' => ['nullable', 'string', Rule::in(['summary', 'summary_large_image', 'app', 'player', ''])],
|
||||
'seo.twitter_default_site' => ['nullable', 'string', 'max:50'],
|
||||
'seo.cache_enabled' => ['nullable', 'boolean'],
|
||||
'seo.cache_ttl' => ['nullable', 'integer', 'min:60', 'max:86400'],
|
||||
'seo.cache_ttl' => ['nullable', 'integer', 'min:'.config('core.settings_limits.seo_cache_ttl_min', 60), 'max:'.config('core.settings_limits.seo_cache_ttl_max', 86400)],
|
||||
'seo.sitemap_enabled' => ['nullable', 'boolean'],
|
||||
'seo.sitemap_cache_ttl' => ['nullable', 'integer', 'min:3600', 'max:604800'],
|
||||
'seo.sitemap_cache_ttl' => ['nullable', 'integer', 'min:'.config('core.settings_limits.seo_sitemap_cache_ttl_min', 3600), 'max:'.config('core.settings_limits.seo_sitemap_cache_ttl_max', 604800)],
|
||||
// 분할 기준. 상한 50000 은 sitemaps.org 프로토콜 제한이며 SitemapWriter 가 동일 값으로 클램프합니다.
|
||||
'seo.sitemap_urls_per_file' => ['nullable', 'integer', 'min:1000', 'max:50000'],
|
||||
'seo.sitemap_urls_per_file' => ['nullable', 'integer', 'min:'.config('core.settings_limits.seo_sitemap_urls_per_file_min', 1000), 'max:'.config('core.settings_limits.seo_sitemap_urls_per_file_max', 50000)],
|
||||
'seo.sitemap_gzip' => ['nullable', 'boolean'],
|
||||
'seo.sitemap_serve_stale_on_miss' => ['nullable', 'boolean'],
|
||||
'seo.sitemap_max_urls_per_contributor' => ['nullable', 'integer', 'min:0'],
|
||||
@@ -243,8 +266,17 @@ class SaveSettingsRequest extends FormRequest
|
||||
'security.force_https' => $this->getTabRules($tab, 'security', 'boolean'),
|
||||
'security.login_attempt_enabled' => $this->getTabRules($tab, 'security', 'boolean'),
|
||||
'security.auth_token_lifetime' => $this->getSecurityTabAuthTokenRules($tab),
|
||||
'security.max_login_attempts' => ['nullable', 'integer', 'min:0', 'max:100'],
|
||||
'security.login_lockout_time' => ['nullable', 'integer', 'min:0', 'max:1440'],
|
||||
'security.max_login_attempts' => ['nullable', 'integer', 'min:'.config('core.settings_limits.security_max_login_attempts_min', 0), 'max:'.config('core.settings_limits.security_max_login_attempts_max', 100)],
|
||||
'security.login_lockout_time' => ['nullable', 'integer', 'min:'.config('core.settings_limits.security_login_lockout_time_min', 0), 'max:'.config('core.settings_limits.security_login_lockout_time_max', 1440)],
|
||||
// 비밀번호 정책 — 저장 규칙이 없어 whitelist 에서 탈락하던 고아 설정을 배선.
|
||||
// 경계값은 config('core.settings_limits') 가 SSoT — 설정 화면도 같은 값을 받아 쓴다.
|
||||
'security.password_min_length' => [
|
||||
'nullable',
|
||||
'integer',
|
||||
'min:'.config('core.settings_limits.security_password_min_length_min', 6),
|
||||
'max:'.config('core.settings_limits.security_password_min_length_max', 64),
|
||||
],
|
||||
'security.require_password_special_char' => ['nullable', 'boolean'],
|
||||
// 신규 설정이므로 미전송(기존 클라이언트)을 허용한다 — 미전송 시 기본값 false 유지
|
||||
'security.allow_internal_outbound_urls' => ['nullable', 'boolean'],
|
||||
|
||||
@@ -258,7 +290,7 @@ class SaveSettingsRequest extends FormRequest
|
||||
'advanced.seo_cache_ttl' => $this->getAdvancedTabCacheTtlRules($tab),
|
||||
// 신규 설정이므로 미전송(기존 클라이언트)을 허용한다 — 미전송/미지정 시 코드 기본값 유지.
|
||||
// 범위는 SEO 탭의 오버라이드 칸(seo.sitemap_cache_ttl)과 동일하게 맞춘다.
|
||||
'advanced.seo_sitemap_cache_ttl' => ['nullable', 'integer', 'min:3600', 'max:604800'],
|
||||
'advanced.seo_sitemap_cache_ttl' => ['nullable', 'integer', 'min:'.config('core.settings_limits.advanced_seo_sitemap_cache_ttl_min', 3600), 'max:'.config('core.settings_limits.advanced_seo_sitemap_cache_ttl_max', 604800)],
|
||||
|
||||
// 디버그 설정 (advanced 탭)
|
||||
'advanced.debug_mode' => $this->getTabRules($tab, 'advanced', 'boolean'),
|
||||
@@ -284,35 +316,35 @@ class SaveSettingsRequest extends FormRequest
|
||||
'drivers.s3_url' => ['nullable', 'url', 'max:500'],
|
||||
'drivers.cache_driver' => $this->getTabRules($tab, 'drivers', [Rule::in(self::SUPPORTED_CACHE_DRIVERS)]),
|
||||
'drivers.redis_host' => ['nullable', 'string', 'max:255'],
|
||||
'drivers.redis_port' => ['nullable', 'integer', 'min:1', 'max:65535'],
|
||||
'drivers.redis_port' => ['nullable', 'integer', 'min:'.config('core.settings_limits.drivers_redis_port_min', 1), 'max:'.config('core.settings_limits.drivers_redis_port_max', 65535)],
|
||||
'drivers.redis_password' => ['nullable', 'string', 'max:255'],
|
||||
'drivers.redis_database' => ['nullable', 'integer', 'min:0', 'max:15'],
|
||||
'drivers.redis_database' => ['nullable', 'integer', 'min:'.config('core.settings_limits.drivers_redis_database_min', 0), 'max:'.config('core.settings_limits.drivers_redis_database_max', 15)],
|
||||
'drivers.memcached_host' => ['nullable', 'string', 'max:255'],
|
||||
'drivers.memcached_port' => ['nullable', 'integer', 'min:1', 'max:65535'],
|
||||
'drivers.memcached_port' => ['nullable', 'integer', 'min:'.config('core.settings_limits.drivers_memcached_port_min', 1), 'max:'.config('core.settings_limits.drivers_memcached_port_max', 65535)],
|
||||
'drivers.session_driver' => $this->getTabRules($tab, 'drivers', [Rule::in(self::SUPPORTED_SESSION_DRIVERS)]),
|
||||
'drivers.session_lifetime' => ['nullable', 'integer', 'min:1', 'max:43200'], // 1분 ~ 30일
|
||||
'drivers.session_lifetime' => ['nullable', 'integer', 'min:'.config('core.settings_limits.drivers_session_lifetime_min', 1), 'max:'.config('core.settings_limits.drivers_session_lifetime_max', 43200)], // 1분 ~ 30일
|
||||
'drivers.queue_driver' => $this->getTabRules($tab, 'drivers', [Rule::in(self::SUPPORTED_QUEUE_DRIVERS)]),
|
||||
'drivers.websocket_enabled' => ['nullable', 'boolean'],
|
||||
'drivers.websocket_app_id' => [Rule::requiredIf(fn () => $this->boolean('drivers.websocket_enabled')), 'nullable', 'string', 'max:255'],
|
||||
'drivers.websocket_app_key' => [Rule::requiredIf(fn () => $this->boolean('drivers.websocket_enabled')), 'nullable', 'string', 'max:255'],
|
||||
'drivers.websocket_app_secret' => [Rule::requiredIf(fn () => $this->boolean('drivers.websocket_enabled')), 'nullable', 'string', 'max:255'],
|
||||
'drivers.websocket_host' => ['nullable', 'string', 'max:255'],
|
||||
'drivers.websocket_port' => ['nullable', 'integer', 'min:1', 'max:65535'],
|
||||
'drivers.websocket_port' => ['nullable', 'integer', 'min:'.config('core.settings_limits.drivers_websocket_port_min', 1), 'max:'.config('core.settings_limits.drivers_websocket_port_max', 65535)],
|
||||
'drivers.websocket_scheme' => ['nullable', Rule::in(self::SUPPORTED_WEBSOCKET_SCHEMES)],
|
||||
'drivers.websocket_verify_ssl' => ['nullable', 'boolean'],
|
||||
'drivers.websocket_server_host' => ['nullable', 'string', 'max:255'],
|
||||
'drivers.websocket_server_port' => ['nullable', 'integer', 'min:1', 'max:65535'],
|
||||
'drivers.websocket_server_port' => ['nullable', 'integer', 'min:'.config('core.settings_limits.drivers_websocket_server_port_min', 1), 'max:'.config('core.settings_limits.drivers_websocket_server_port_max', 65535)],
|
||||
'drivers.websocket_server_scheme' => ['nullable', Rule::in(self::SUPPORTED_WEBSOCKET_SCHEMES)],
|
||||
'drivers.search_engine_driver' => ['nullable', Rule::in($this->getSupportedSearchEngineDrivers())],
|
||||
'drivers.log_driver' => $this->getTabRules($tab, 'drivers', [Rule::in(self::SUPPORTED_LOG_DRIVERS)]),
|
||||
'drivers.log_level' => $this->getTabRules($tab, 'drivers', [Rule::in(self::SUPPORTED_LOG_LEVELS)]),
|
||||
'drivers.log_days' => ['nullable', 'integer', 'min:1', 'max:365'],
|
||||
'drivers.log_days' => ['nullable', 'integer', 'min:'.config('core.settings_limits.drivers_log_days_min', 1), 'max:'.config('core.settings_limits.drivers_log_days_max', 365)],
|
||||
|
||||
// 본인인증(IDV) provider 기술 파라미터 — 정책 분기는 IdentityPolicy 로 흡수됨
|
||||
'identity.default_provider' => ['nullable', 'string', 'max:100'],
|
||||
'identity.purpose_providers' => ['sometimes', 'array'],
|
||||
'identity.challenge_ttl_minutes' => $this->getTabRules($tab, 'identity', 'integer|min:1|max:1440'),
|
||||
'identity.max_attempts' => $this->getTabRules($tab, 'identity', 'integer|min:1|max:20'),
|
||||
'identity.challenge_ttl_minutes' => $this->getTabRules($tab, 'identity', 'integer|min:'.config('core.settings_limits.identity_challenge_ttl_minutes_min', 1).'|max:'.config('core.settings_limits.identity_challenge_ttl_minutes_max', 1440)),
|
||||
'identity.max_attempts' => $this->getTabRules($tab, 'identity', 'integer|min:'.config('core.settings_limits.identity_max_attempts_min', 1).'|max:'.config('core.settings_limits.identity_max_attempts_max', 20)),
|
||||
];
|
||||
|
||||
// 모듈/플러그인이 validation rules를 동적으로 추가할 수 있도록 훅 제공
|
||||
@@ -374,8 +406,8 @@ class SaveSettingsRequest extends FormRequest
|
||||
return [
|
||||
'nullable',
|
||||
'integer',
|
||||
'min:0',
|
||||
'max:3600',
|
||||
'min:'.config('core.settings_limits.security_auth_token_lifetime_min', 0),
|
||||
'max:'.config('core.settings_limits.security_auth_token_lifetime_max', 3600),
|
||||
function ($attribute, $value, $fail) {
|
||||
// 0은 무한대를 의미하므로 허용, 그 외에는 30 이상이어야 함
|
||||
if ($value !== null && $value !== 0 && $value < 30) {
|
||||
@@ -436,8 +468,8 @@ class SaveSettingsRequest extends FormRequest
|
||||
|
||||
return array_merge($baseRules, [
|
||||
'integer',
|
||||
'min:0',
|
||||
'max:14400',
|
||||
'min:'.config('core.settings_limits.advanced_cache_ttl_min', 0),
|
||||
'max:'.config('core.settings_limits.advanced_cache_ttl_max', 14400),
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -780,6 +812,119 @@ class SaveSettingsRequest extends FormRequest
|
||||
'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'),
|
||||
// general
|
||||
'general.currency' => __('validation.attributes.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.encryption' => __('validation.attributes.encryption'),
|
||||
'mail.mailgun_domain' => __('validation.attributes.mailgun_domain'),
|
||||
'mail.mailgun_secret' => __('validation.attributes.mailgun_secret'),
|
||||
'mail.mailgun_endpoint' => __('validation.attributes.mailgun_endpoint'),
|
||||
'mail.ses_key' => __('validation.attributes.ses_key'),
|
||||
'mail.ses_secret' => __('validation.attributes.ses_secret'),
|
||||
'mail.ses_region' => __('validation.attributes.ses_region'),
|
||||
'mail.from_address' => __('validation.attributes.from_address'),
|
||||
'mail.from_name' => __('validation.attributes.from_name'),
|
||||
// upload
|
||||
'upload.max_file_size' => __('validation.attributes.max_file_size'),
|
||||
'upload.allowed_extensions' => __('validation.attributes.allowed_extensions'),
|
||||
'upload.image_max_width' => __('validation.attributes.image_max_width'),
|
||||
'upload.image_max_height' => __('validation.attributes.image_max_height'),
|
||||
'upload.image_quality' => __('validation.attributes.image_quality'),
|
||||
// seo
|
||||
'seo.meta_title_suffix' => __('validation.attributes.meta_title_suffix'),
|
||||
'seo.meta_description' => __('validation.attributes.meta_description'),
|
||||
'seo.meta_keywords' => __('validation.attributes.meta_keywords'),
|
||||
'seo.google_analytics_id' => __('validation.attributes.google_analytics_id'),
|
||||
'seo.google_site_verification' => __('validation.attributes.google_site_verification'),
|
||||
'seo.naver_site_verification' => __('validation.attributes.naver_site_verification'),
|
||||
'seo.bot_user_agents' => __('validation.attributes.bot_user_agents'),
|
||||
'seo.bot_detection_enabled' => __('validation.attributes.bot_detection_enabled'),
|
||||
'seo.bot_detection_library_enabled' => __('validation.attributes.bot_detection_library_enabled'),
|
||||
'seo.og_default_site_name' => __('validation.attributes.og_default_site_name'),
|
||||
'seo.og_image_default_width' => __('validation.attributes.og_image_default_width'),
|
||||
'seo.og_image_default_height' => __('validation.attributes.og_image_default_height'),
|
||||
'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.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'),
|
||||
'seo.sitemap_gzip' => __('validation.attributes.sitemap_gzip'),
|
||||
'seo.sitemap_serve_stale_on_miss' => __('validation.attributes.sitemap_serve_stale_on_miss'),
|
||||
'seo.sitemap_max_urls_per_contributor' => __('validation.attributes.sitemap_max_urls_per_contributor'),
|
||||
'seo.sitemap_hreflang_enabled' => __('validation.attributes.sitemap_hreflang_enabled'),
|
||||
'seo.sitemap_schedule' => __('validation.attributes.sitemap_schedule'),
|
||||
'seo.sitemap_schedule_time' => __('validation.attributes.sitemap_schedule_time'),
|
||||
'seo.generator_enabled' => __('validation.attributes.generator_enabled'),
|
||||
'seo.generator_content' => __('validation.attributes.generator_content'),
|
||||
// security
|
||||
'security.force_https' => __('validation.attributes.force_https'),
|
||||
'security.login_attempt_enabled' => __('validation.attributes.login_attempt_enabled'),
|
||||
'security.auth_token_lifetime' => __('validation.attributes.auth_token_lifetime'),
|
||||
'security.max_login_attempts' => __('validation.attributes.max_login_attempts'),
|
||||
'security.login_lockout_time' => __('validation.attributes.login_lockout_time'),
|
||||
'security.password_min_length' => __('validation.attributes.password_min_length'),
|
||||
'security.require_password_special_char' => __('validation.attributes.require_password_special_char'),
|
||||
'security.allow_internal_outbound_urls' => __('validation.attributes.allow_internal_outbound_urls'),
|
||||
// advanced
|
||||
'advanced.cache_enabled' => __('validation.attributes.advanced_cache_enabled'),
|
||||
'advanced.layout_cache_enabled' => __('validation.attributes.layout_cache_enabled'),
|
||||
'advanced.layout_cache_ttl' => __('validation.attributes.layout_cache_ttl'),
|
||||
'advanced.stats_cache_enabled' => __('validation.attributes.stats_cache_enabled'),
|
||||
'advanced.stats_cache_ttl' => __('validation.attributes.stats_cache_ttl'),
|
||||
'advanced.seo_cache_enabled' => __('validation.attributes.seo_cache_enabled'),
|
||||
'advanced.seo_cache_ttl' => __('validation.attributes.seo_cache_ttl'),
|
||||
'advanced.seo_sitemap_cache_ttl' => __('validation.attributes.seo_sitemap_cache_ttl'),
|
||||
'advanced.debug_mode' => __('validation.attributes.debug_mode'),
|
||||
'advanced.sql_query_log' => __('validation.attributes.sql_query_log'),
|
||||
'advanced.core_update_github_url' => __('validation.attributes.core_update_github_url'),
|
||||
'advanced.core_update_github_token' => __('validation.attributes.core_update_github_token'),
|
||||
'advanced.geoip_enabled' => __('validation.attributes.geoip_enabled'),
|
||||
'advanced.geoip_license_key' => __('validation.attributes.geoip_license_key'),
|
||||
'advanced.geoip_auto_update_enabled' => __('validation.attributes.geoip_auto_update_enabled'),
|
||||
// drivers
|
||||
'drivers.storage_driver' => __('validation.attributes.storage_driver'),
|
||||
'drivers.s3_bucket' => __('validation.attributes.s3_bucket'),
|
||||
'drivers.s3_region' => __('validation.attributes.s3_region'),
|
||||
'drivers.s3_access_key' => __('validation.attributes.s3_access_key'),
|
||||
'drivers.s3_secret_key' => __('validation.attributes.s3_secret_key'),
|
||||
'drivers.s3_url' => __('validation.attributes.s3_url'),
|
||||
'drivers.cache_driver' => __('validation.attributes.cache_driver'),
|
||||
'drivers.redis_host' => __('validation.attributes.redis_host'),
|
||||
'drivers.redis_port' => __('validation.attributes.redis_port'),
|
||||
'drivers.redis_password' => __('validation.attributes.redis_password'),
|
||||
'drivers.redis_database' => __('validation.attributes.redis_database'),
|
||||
'drivers.memcached_host' => __('validation.attributes.memcached_host'),
|
||||
'drivers.memcached_port' => __('validation.attributes.memcached_port'),
|
||||
'drivers.session_driver' => __('validation.attributes.session_driver'),
|
||||
'drivers.session_lifetime' => __('validation.attributes.session_lifetime'),
|
||||
'drivers.queue_driver' => __('validation.attributes.queue_driver'),
|
||||
'drivers.websocket_enabled' => __('validation.attributes.websocket_enabled'),
|
||||
'drivers.websocket_app_id' => __('validation.attributes.websocket_app_id'),
|
||||
'drivers.websocket_app_key' => __('validation.attributes.websocket_app_key'),
|
||||
'drivers.websocket_app_secret' => __('validation.attributes.websocket_app_secret'),
|
||||
'drivers.websocket_host' => __('validation.attributes.websocket_host'),
|
||||
'drivers.websocket_port' => __('validation.attributes.websocket_port'),
|
||||
'drivers.websocket_scheme' => __('validation.attributes.websocket_scheme'),
|
||||
'drivers.websocket_verify_ssl' => __('validation.attributes.websocket_verify_ssl'),
|
||||
'drivers.websocket_server_host' => __('validation.attributes.websocket_server_host'),
|
||||
'drivers.websocket_server_port' => __('validation.attributes.websocket_server_port'),
|
||||
'drivers.websocket_server_scheme' => __('validation.attributes.websocket_server_scheme'),
|
||||
'drivers.search_engine_driver' => __('validation.attributes.search_engine_driver'),
|
||||
'drivers.log_driver' => __('validation.attributes.log_driver'),
|
||||
'drivers.log_level' => __('validation.attributes.log_level'),
|
||||
'drivers.log_days' => __('validation.attributes.log_days'),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -3,8 +3,9 @@
|
||||
namespace App\Http\Requests\User;
|
||||
|
||||
use App\Extension\HookManager;
|
||||
use App\Rules\PasswordPolicy;
|
||||
use Illuminate\Contracts\Validation\ValidationRule;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Validation\Rules\Password;
|
||||
|
||||
/**
|
||||
* 비밀번호 변경 요청 클래스
|
||||
@@ -15,6 +16,8 @@ class ChangePasswordRequest extends FormRequest
|
||||
{
|
||||
/**
|
||||
* Determine if the user is authorized to make this request.
|
||||
*
|
||||
* @return bool 항상 true (권한은 미들웨어에서 검증)
|
||||
*/
|
||||
public function authorize(): bool
|
||||
{
|
||||
@@ -24,13 +27,13 @@ class ChangePasswordRequest extends FormRequest
|
||||
/**
|
||||
* Get the validation rules that apply to the request.
|
||||
*
|
||||
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
|
||||
* @return array<string, ValidationRule|array<mixed>|string>
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
$rules = [
|
||||
'current_password' => ['required', 'string', 'current_password:sanctum'],
|
||||
'password' => ['required', 'string', 'confirmed', Password::min(8)],
|
||||
'password' => ['required', 'string', 'confirmed', PasswordPolicy::rule()],
|
||||
'password_confirmation' => ['required', 'string'],
|
||||
];
|
||||
|
||||
@@ -54,4 +57,4 @@ class ChangePasswordRequest extends FormRequest
|
||||
'password_confirmation.required' => __('user.validation.password_confirmation_required'),
|
||||
];
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -5,14 +5,17 @@ namespace App\Http\Requests\User;
|
||||
use App\Extension\HookManager;
|
||||
use App\Models\Role;
|
||||
use App\Models\User;
|
||||
use App\Rules\PasswordPolicy;
|
||||
use Illuminate\Contracts\Validation\ValidationRule;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Validation\Rule;
|
||||
use Illuminate\Validation\Rules\Password;
|
||||
|
||||
class CreateUserRequest extends FormRequest
|
||||
{
|
||||
/**
|
||||
* Determine if the user is authorized to make this request.
|
||||
*
|
||||
* @return bool 항상 true (권한은 미들웨어에서 검증)
|
||||
*/
|
||||
public function authorize(): bool
|
||||
{
|
||||
@@ -22,7 +25,7 @@ class CreateUserRequest extends FormRequest
|
||||
/**
|
||||
* Get the validation rules that apply to the request.
|
||||
*
|
||||
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
|
||||
* @return array<string, ValidationRule|array<mixed>|string>
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
@@ -33,7 +36,7 @@ class CreateUserRequest extends FormRequest
|
||||
'name' => 'required|string|max:255',
|
||||
'nickname' => 'nullable|string|max:50',
|
||||
'email' => ['required', 'email', Rule::unique(User::class, 'email'), 'max:255'],
|
||||
'password' => ['required', 'confirmed', Password::min(8)],
|
||||
'password' => ['required', 'confirmed', PasswordPolicy::rule()],
|
||||
'language' => 'nullable|string|in:'.$supportedLocales,
|
||||
'country' => 'nullable|string|size:2|alpha',
|
||||
'timezone' => ['nullable', 'string', 'timezone'],
|
||||
@@ -122,8 +125,6 @@ class CreateUserRequest extends FormRequest
|
||||
* 유효성 검사를 위해 데이터를 준비합니다.
|
||||
*
|
||||
* role_ids와 roles가 동시에 전송될 경우 role_ids를 우선하여 roles를 제거합니다.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected function prepareForValidation(): void
|
||||
{
|
||||
|
||||
@@ -4,6 +4,8 @@ namespace App\Http\Requests\User;
|
||||
|
||||
use App\Extension\HookManager;
|
||||
use App\Models\User;
|
||||
use App\Rules\PasswordPolicy;
|
||||
use Illuminate\Contracts\Validation\ValidationRule;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Validation\Rule;
|
||||
@@ -19,6 +21,8 @@ class UpdateProfileRequest extends FormRequest
|
||||
{
|
||||
/**
|
||||
* Determine if the user is authorized to make this request.
|
||||
*
|
||||
* @return bool 항상 true (권한은 미들웨어에서 검증)
|
||||
*/
|
||||
public function authorize(): bool
|
||||
{
|
||||
@@ -28,7 +32,7 @@ class UpdateProfileRequest extends FormRequest
|
||||
/**
|
||||
* Get the validation rules that apply to the request.
|
||||
*
|
||||
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
|
||||
* @return array<string, ValidationRule|array<mixed>|string>
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
@@ -40,7 +44,7 @@ class UpdateProfileRequest extends FormRequest
|
||||
'name' => ['required', 'string', 'max:255'],
|
||||
'nickname' => ['nullable', 'string', 'max:50'],
|
||||
'email' => ['required', 'email', 'max:255', Rule::unique(User::class, 'email')->ignore($userId)],
|
||||
'password' => ['nullable', 'confirmed', Password::min(8)],
|
||||
'password' => ['nullable', 'confirmed', PasswordPolicy::rule()],
|
||||
'current_password' => ['required_with:password', 'current_password'],
|
||||
'language' => ['nullable', 'string', Rule::in($supportedLocales)],
|
||||
'country' => ['nullable', 'string', 'size:2', 'alpha'],
|
||||
@@ -124,5 +128,4 @@ class UpdateProfileRequest extends FormRequest
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -5,14 +5,17 @@ namespace App\Http\Requests\User;
|
||||
use App\Extension\HookManager;
|
||||
use App\Models\Role;
|
||||
use App\Models\User;
|
||||
use App\Rules\PasswordPolicy;
|
||||
use Illuminate\Contracts\Validation\ValidationRule;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Validation\Rule;
|
||||
use Illuminate\Validation\Rules\Password;
|
||||
|
||||
class UpdateUserRequest extends FormRequest
|
||||
{
|
||||
/**
|
||||
* Determine if the user is authorized to make this request.
|
||||
*
|
||||
* @return bool 항상 true (권한은 permission 미들웨어에서 검증)
|
||||
*/
|
||||
public function authorize(): bool
|
||||
{
|
||||
@@ -24,8 +27,6 @@ class UpdateUserRequest extends FormRequest
|
||||
*
|
||||
* API 응답에서 로드된 roles(객체 배열)와 사용자가 선택한 role_ids가
|
||||
* 동시에 전송될 수 있으므로, role_ids가 있으면 roles를 제거합니다.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected function prepareForValidation(): void
|
||||
{
|
||||
@@ -37,7 +38,7 @@ class UpdateUserRequest extends FormRequest
|
||||
/**
|
||||
* Get the validation rules that apply to the request.
|
||||
*
|
||||
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
|
||||
* @return array<string, ValidationRule|array<mixed>|string>
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
@@ -54,7 +55,7 @@ class UpdateUserRequest extends FormRequest
|
||||
'max:255',
|
||||
Rule::unique(User::class, 'email')->ignore($userId),
|
||||
],
|
||||
'password' => ['nullable', 'confirmed', Password::min(8)],
|
||||
'password' => ['nullable', 'confirmed', PasswordPolicy::rule()],
|
||||
'language' => 'nullable|string|in:'.$supportedLocales,
|
||||
'country' => 'nullable|string|size:2|alpha',
|
||||
'timezone' => ['nullable', 'string', 'timezone'],
|
||||
|
||||
@@ -260,6 +260,14 @@ class UserResource extends BaseApiResource
|
||||
'blocked_at' => $this->getValue('blocked_at')
|
||||
? $this->formatDateTimeStringForUser($this->getValue('blocked_at'))
|
||||
: null,
|
||||
// 로그인 실패 누적 잠금 상태 — 관리자만 확인·해제할 수 있어야 하므로 관리자 응답에만 노출
|
||||
'failed_login_attempts' => (int) ($this->getValue('failed_login_attempts') ?? 0),
|
||||
'locked_permanently' => (bool) $this->getValue('locked_permanently'),
|
||||
'locked_until' => $this->getValue('locked_until')
|
||||
? $this->formatDateTimeStringForUser($this->getValue('locked_until'))
|
||||
: null,
|
||||
'is_locked' => (bool) $this->getValue('locked_permanently')
|
||||
|| ($this->getValue('locked_until') !== null && $this->resource->locked_until?->isFuture()),
|
||||
]);
|
||||
|
||||
// Filter 훅: 모듈이 자신의 데이터를 응답에 병합
|
||||
|
||||
@@ -1,10 +1,14 @@
|
||||
<?php
|
||||
|
||||
// audit:allow job-generator-needs-scale-test 이번 변경은 리스너 1건을 해석하는 지점에 가드를 더한 것으로,
|
||||
// 처리 건수에 따라 동작이 달라지는 경로(배치·생성기)를 도입하지 않는다. 디스패치 단위 의미는 종전과 동일.
|
||||
|
||||
namespace App\Jobs;
|
||||
|
||||
use App\Extension\HookArgumentSerializer;
|
||||
use App\Extension\HookContextCapture;
|
||||
use Illuminate\Bus\Queueable;
|
||||
use Illuminate\Contracts\Container\BindingResolutionException;
|
||||
use Illuminate\Contracts\Queue\ShouldQueue;
|
||||
use Illuminate\Foundation\Bus\Dispatchable;
|
||||
use Illuminate\Queue\InteractsWithQueue;
|
||||
@@ -23,8 +27,6 @@ class DispatchHookListenerJob implements ShouldQueue
|
||||
|
||||
/**
|
||||
* 최대 재시도 횟수
|
||||
*
|
||||
* @var int
|
||||
*/
|
||||
public int $tries = 3;
|
||||
|
||||
@@ -45,24 +47,48 @@ class DispatchHookListenerJob implements ShouldQueue
|
||||
|
||||
/**
|
||||
* Job을 실행합니다.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function handle(): void
|
||||
{
|
||||
// 큐 워커 컨텍스트에 원래 요청의 Auth/Request/Locale 복원
|
||||
// (Job 종료 시 컨테이너 폐기되므로 finally 원복 불필요)
|
||||
HookContextCapture::restore($this->context);
|
||||
// 큐 드라이버가 sync 면 이 Job 은 원 HTTP 요청과 **같은 컨테이너**에서 실행된다.
|
||||
// restore() 가 재구성 Request 를 바인딩하면 그 뒤로 이어지는 같은 요청의 코드는
|
||||
// 헤더·입력·메서드가 전부 지워진 가짜 GET 요청을 보게 된다 — 뒤 순위 훅 리스너가
|
||||
// 전송 헤더를 읽지 못해 조용히 건너뛰는 사고가 여기서 난다.
|
||||
// 워커 프로세스에서는 원래 바인딩이 없어 아래 원복이 아무 일도 하지 않는다.
|
||||
$previousRequest = app()->bound('request') ? app('request') : null;
|
||||
|
||||
$args = HookArgumentSerializer::deserialize($this->serializedArgs);
|
||||
app($this->listenerClass)->{$this->method}(...$args);
|
||||
try {
|
||||
HookContextCapture::restore($this->context);
|
||||
|
||||
$args = HookArgumentSerializer::deserialize($this->serializedArgs);
|
||||
|
||||
try {
|
||||
$listener = app($this->listenerClass);
|
||||
} catch (BindingResolutionException $e) {
|
||||
// 리스너를 만들 수 없다는 것은 그 확장이 이 런타임에 배선되지 않았다는 뜻이다.
|
||||
// Action 훅은 부가 작업이므로 호출자의 작업까지 함께 실패시키지 않고 기록만 남긴다
|
||||
// (큐 드라이버가 sync 인 환경에서 원 요청이 500 이 되는 것을 막는다).
|
||||
Log::warning('훅 리스너를 해석할 수 없어 건너뜁니다 (확장 미배선)', [
|
||||
'listener' => $this->listenerClass,
|
||||
'method' => $this->method,
|
||||
'exception' => $e->getMessage(),
|
||||
]);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$listener->{$this->method}(...$args);
|
||||
} finally {
|
||||
if ($previousRequest !== null) {
|
||||
app()->instance('request', $previousRequest);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Job 실패 시 로그를 기록합니다.
|
||||
*
|
||||
* @param \Throwable $exception 발생한 예외
|
||||
* @return void
|
||||
*/
|
||||
public function failed(\Throwable $exception): void
|
||||
{
|
||||
@@ -76,8 +102,6 @@ class DispatchHookListenerJob implements ShouldQueue
|
||||
|
||||
/**
|
||||
* Job의 표시 이름을 반환합니다.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function displayName(): string
|
||||
{
|
||||
|
||||
@@ -8,8 +8,10 @@ use App\Contracts\Extension\HookListenerInterface;
|
||||
use App\Contracts\Repositories\ActivityLogRepositoryInterface;
|
||||
use App\Contracts\Repositories\ScheduleRepositoryInterface;
|
||||
use App\Contracts\Repositories\UserRepositoryInterface;
|
||||
use App\Models\ActivityLog;
|
||||
use App\Extension\IdentityVerification\DTO\VerificationChallenge;
|
||||
use App\Extension\IdentityVerification\DTO\VerificationResult;
|
||||
use App\Models\Attachment;
|
||||
use App\Models\IdentityVerificationLog;
|
||||
use App\Models\Schedule;
|
||||
use App\Models\User;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
@@ -65,6 +67,7 @@ class CoreActivityLogListener implements HookListenerInterface
|
||||
'core.auth.record_consents' => ['method' => 'handleAuthRecordConsents', 'priority' => 20],
|
||||
'core.auth.login_failed' => ['method' => 'handleAuthLoginFailed', 'priority' => 20],
|
||||
'core.auth.account_locked' => ['method' => 'handleAuthAccountLocked', 'priority' => 20],
|
||||
'core.auth.account_unlocked' => ['method' => 'handleAuthAccountUnlocked', 'priority' => 20],
|
||||
|
||||
// ─── IdentityVerification (IDV) ───
|
||||
// DTO(VerificationChallenge/VerificationResult) 를 인자로 받으므로 sync 실행 필수
|
||||
@@ -145,7 +148,7 @@ class CoreActivityLogListener implements HookListenerInterface
|
||||
/**
|
||||
* 훅 이벤트 처리 (기본 핸들러)
|
||||
*
|
||||
* @param mixed ...$args 훅에서 전달된 인수들
|
||||
* @param mixed ...$args 훅에서 전달된 인수들
|
||||
*/
|
||||
public function handle(...$args): void
|
||||
{
|
||||
@@ -159,8 +162,8 @@ class CoreActivityLogListener implements HookListenerInterface
|
||||
/**
|
||||
* 사용자 생성 후 로그 기록
|
||||
*
|
||||
* @param User $user 생성된 사용자
|
||||
* @param array $originalData 원본 요청 데이터
|
||||
* @param User $user 생성된 사용자
|
||||
* @param array $originalData 원본 요청 데이터
|
||||
*/
|
||||
public function handleUserAfterCreate(User $user, array $originalData): void
|
||||
{
|
||||
@@ -175,9 +178,9 @@ class CoreActivityLogListener implements HookListenerInterface
|
||||
/**
|
||||
* 사용자 수정 후 로그 기록
|
||||
*
|
||||
* @param User $user 수정된 사용자
|
||||
* @param array $originalData 원본 요청 데이터
|
||||
* @param array|null $snapshot 수정 전 스냅샷
|
||||
* @param User $user 수정된 사용자
|
||||
* @param array $originalData 원본 요청 데이터
|
||||
* @param array|null $snapshot 수정 전 스냅샷
|
||||
*/
|
||||
public function handleUserAfterUpdate(User $user, array $originalData, ?array $snapshot = null): void
|
||||
{
|
||||
@@ -194,7 +197,7 @@ class CoreActivityLogListener implements HookListenerInterface
|
||||
/**
|
||||
* 사용자 삭제 후 로그 기록
|
||||
*
|
||||
* @param array $userData 삭제된 사용자 데이터
|
||||
* @param array $userData 삭제된 사용자 데이터
|
||||
*/
|
||||
public function handleUserAfterDelete(array $userData): void
|
||||
{
|
||||
@@ -213,7 +216,7 @@ class CoreActivityLogListener implements HookListenerInterface
|
||||
/**
|
||||
* 사용자 탈퇴 후 로그 기록
|
||||
*
|
||||
* @param User $user 탈퇴한 사용자
|
||||
* @param User $user 탈퇴한 사용자
|
||||
*/
|
||||
public function handleUserAfterWithdraw(User $user): void
|
||||
{
|
||||
@@ -227,7 +230,7 @@ class CoreActivityLogListener implements HookListenerInterface
|
||||
/**
|
||||
* 사용자 상세 조회 후 로그 기록
|
||||
*
|
||||
* @param User $user 조회된 사용자
|
||||
* @param User $user 조회된 사용자
|
||||
*/
|
||||
public function handleUserAfterShow(User $user): void
|
||||
{
|
||||
@@ -241,7 +244,7 @@ class CoreActivityLogListener implements HookListenerInterface
|
||||
/**
|
||||
* 사용자 목록 조회 후 로그 기록
|
||||
*
|
||||
* @param int $count 조회된 총 사용자 수
|
||||
* @param int $count 조회된 총 사용자 수
|
||||
*/
|
||||
public function handleUserAfterList(int $count): void
|
||||
{
|
||||
@@ -254,8 +257,8 @@ class CoreActivityLogListener implements HookListenerInterface
|
||||
/**
|
||||
* 사용자 검색 후 로그 기록
|
||||
*
|
||||
* @param string $query 검색어
|
||||
* @param int $count 검색 결과 수
|
||||
* @param string $query 검색어
|
||||
* @param int $count 검색 결과 수
|
||||
*/
|
||||
public function handleUserAfterSearch(string $query, int $count): void
|
||||
{
|
||||
@@ -268,10 +271,10 @@ class CoreActivityLogListener implements HookListenerInterface
|
||||
/**
|
||||
* 사용자 일괄 상태 변경 후 로그 기록
|
||||
*
|
||||
* @param array $uuids 대상 UUID 목록
|
||||
* @param string $status 변경된 상태
|
||||
* @param int $updatedCount 변경된 수
|
||||
* @param array $snapshots 변경 전 스냅샷 (uuid => snapshot)
|
||||
* @param array $uuids 대상 UUID 목록
|
||||
* @param string $status 변경된 상태
|
||||
* @param int $updatedCount 변경된 수
|
||||
* @param array $snapshots 변경 전 스냅샷 (uuid => snapshot)
|
||||
*/
|
||||
public function handleUserAfterBulkUpdate(array $uuids, string $status, int $updatedCount, array $snapshots = []): void
|
||||
{
|
||||
@@ -303,8 +306,8 @@ class CoreActivityLogListener implements HookListenerInterface
|
||||
/**
|
||||
* 관리자 로그인 후 로그 기록
|
||||
*
|
||||
* @param User $user 로그인한 사용자
|
||||
* @param array $loginData 로그인 데이터
|
||||
* @param User $user 로그인한 사용자
|
||||
* @param array $loginData 로그인 데이터
|
||||
*/
|
||||
public function handleAuthAfterLogin(User $user, array $loginData): void
|
||||
{
|
||||
@@ -318,7 +321,7 @@ class CoreActivityLogListener implements HookListenerInterface
|
||||
/**
|
||||
* 로그아웃 로그 기록
|
||||
*
|
||||
* @param User $user 로그아웃한 사용자
|
||||
* @param User $user 로그아웃한 사용자
|
||||
*/
|
||||
public function handleAuthLogout(User $user): void
|
||||
{
|
||||
@@ -332,8 +335,8 @@ class CoreActivityLogListener implements HookListenerInterface
|
||||
/**
|
||||
* 회원가입 후 로그 기록
|
||||
*
|
||||
* @param User $user 등록된 사용자
|
||||
* @param array $registrationData 등록 데이터
|
||||
* @param User $user 등록된 사용자
|
||||
* @param array $registrationData 등록 데이터
|
||||
*/
|
||||
public function handleAuthRegister(User $user, array $registrationData): void
|
||||
{
|
||||
@@ -347,7 +350,7 @@ class CoreActivityLogListener implements HookListenerInterface
|
||||
/**
|
||||
* 비밀번호 찾기 요청 로그 기록
|
||||
*
|
||||
* @param User $user 요청한 사용자
|
||||
* @param User $user 요청한 사용자
|
||||
*/
|
||||
public function handleAuthForgotPassword(User $user): void
|
||||
{
|
||||
@@ -361,7 +364,7 @@ class CoreActivityLogListener implements HookListenerInterface
|
||||
/**
|
||||
* 비밀번호 재설정 로그 기록
|
||||
*
|
||||
* @param User $user 재설정한 사용자
|
||||
* @param User $user 재설정한 사용자
|
||||
*/
|
||||
public function handleAuthResetPassword(User $user): void
|
||||
{
|
||||
@@ -375,10 +378,10 @@ class CoreActivityLogListener implements HookListenerInterface
|
||||
/**
|
||||
* 이용약관 동의 기록 로그
|
||||
*
|
||||
* @param User $user 동의한 사용자
|
||||
* @param array $data 동의 데이터
|
||||
* @param string|null $agreedAt 동의 시각 (DispatchHookListenerJob 역직렬화 과정에서 null 가능)
|
||||
* @param string|null $ip IP 주소
|
||||
* @param User $user 동의한 사용자
|
||||
* @param array $data 동의 데이터
|
||||
* @param string|null $agreedAt 동의 시각 (DispatchHookListenerJob 역직렬화 과정에서 null 가능)
|
||||
* @param string|null $ip IP 주소
|
||||
*/
|
||||
public function handleAuthRecordConsents(User $user, array $data, ?string $agreedAt = null, ?string $ip = null): void
|
||||
{
|
||||
@@ -393,8 +396,8 @@ class CoreActivityLogListener implements HookListenerInterface
|
||||
/**
|
||||
* 로그인 실패 로그 기록 (사용자 존재 여부와 무관)
|
||||
*
|
||||
* @param string $email 시도된 이메일
|
||||
* @param array $context IP/UA/시각 등 부가 정보
|
||||
* @param string $email 시도된 이메일
|
||||
* @param array $context IP/UA/시각 등 부가 정보
|
||||
*/
|
||||
public function handleAuthLoginFailed(string $email, array $context = []): void
|
||||
{
|
||||
@@ -408,14 +411,19 @@ class CoreActivityLogListener implements HookListenerInterface
|
||||
/**
|
||||
* 계정 잠금 로그 기록
|
||||
*
|
||||
* @param User $user 잠긴 사용자
|
||||
* @param array $context attempts/locked_until/lockout_minutes/IP
|
||||
* @param User $user 잠긴 사용자
|
||||
* @param array $context attempts/locked_until/lockout_minutes/IP
|
||||
*/
|
||||
public function handleAuthAccountLocked(User $user, array $context = []): void
|
||||
{
|
||||
// 영구 잠금(무한대)은 차단 분(minutes)이 없으므로 별도 문구를 사용한다.
|
||||
$permanent = ($context['permanent'] ?? false) || ($context['locked_until'] ?? null) === null;
|
||||
|
||||
$this->logActivity('auth.account_locked', [
|
||||
'loggable' => $user,
|
||||
'description_key' => 'activity_log.description.auth_account_locked',
|
||||
'description_key' => $permanent
|
||||
? 'activity_log.description.auth_account_locked_permanently'
|
||||
: 'activity_log.description.auth_account_locked',
|
||||
'description_params' => [
|
||||
'attempts' => $context['attempts'] ?? null,
|
||||
'minutes' => $context['lockout_minutes'] ?? null,
|
||||
@@ -425,6 +433,22 @@ class CoreActivityLogListener implements HookListenerInterface
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 계정 잠금 해제 로그 기록 (관리자 수동 해제)
|
||||
*
|
||||
* @param User $user 잠금이 해제된 사용자
|
||||
* @param array $context IP 등 부가 정보
|
||||
*/
|
||||
public function handleAuthAccountUnlocked(User $user, array $context = []): void
|
||||
{
|
||||
$this->logActivity('auth.account_unlocked', [
|
||||
'loggable' => $user,
|
||||
'description_key' => 'activity_log.description.auth_account_unlocked',
|
||||
'description_params' => ['email' => $user->email],
|
||||
'ip_address' => $context['ip_address'] ?? null,
|
||||
]);
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════
|
||||
// Role 핸들러
|
||||
// ═══════════════════════════════════════════
|
||||
@@ -432,7 +456,7 @@ class CoreActivityLogListener implements HookListenerInterface
|
||||
/**
|
||||
* 역할 생성 후 로그 기록
|
||||
*
|
||||
* @param Model $role 생성된 역할
|
||||
* @param Model $role 생성된 역할
|
||||
*/
|
||||
public function handleRoleAfterCreate(Model $role): void
|
||||
{
|
||||
@@ -447,8 +471,8 @@ class CoreActivityLogListener implements HookListenerInterface
|
||||
/**
|
||||
* 역할 수정 후 로그 기록
|
||||
*
|
||||
* @param Model $role 수정된 역할
|
||||
* @param array|null $snapshot 수정 전 스냅샷
|
||||
* @param Model $role 수정된 역할
|
||||
* @param array|null $snapshot 수정 전 스냅샷
|
||||
*/
|
||||
public function handleRoleAfterUpdate(Model $role, ?array $snapshot = null): void
|
||||
{
|
||||
@@ -465,7 +489,7 @@ class CoreActivityLogListener implements HookListenerInterface
|
||||
/**
|
||||
* 역할 삭제 후 로그 기록
|
||||
*
|
||||
* @param int $roleId 삭제된 역할 ID
|
||||
* @param int $roleId 삭제된 역할 ID
|
||||
*/
|
||||
public function handleRoleAfterDelete(int $roleId): void
|
||||
{
|
||||
@@ -479,9 +503,9 @@ class CoreActivityLogListener implements HookListenerInterface
|
||||
/**
|
||||
* 역할 권한 동기화 후 로그 기록
|
||||
*
|
||||
* @param Model $role 역할
|
||||
* @param array $previousPermissions 이전 권한 목록
|
||||
* @param array $currentPermissions 현재 권한 목록
|
||||
* @param Model $role 역할
|
||||
* @param array $previousPermissions 이전 권한 목록
|
||||
* @param array $currentPermissions 현재 권한 목록
|
||||
*/
|
||||
public function handleRoleAfterSyncPermissions(Model $role, array $previousPermissions, array $currentPermissions): void
|
||||
{
|
||||
@@ -499,7 +523,7 @@ class CoreActivityLogListener implements HookListenerInterface
|
||||
/**
|
||||
* 역할 상태 전환 후 로그 기록
|
||||
*
|
||||
* @param Model $role 역할
|
||||
* @param Model $role 역할
|
||||
*/
|
||||
public function handleRoleAfterToggleStatus(Model $role): void
|
||||
{
|
||||
@@ -517,7 +541,7 @@ class CoreActivityLogListener implements HookListenerInterface
|
||||
/**
|
||||
* 메뉴 생성 후 로그 기록
|
||||
*
|
||||
* @param Model $menu 생성된 메뉴
|
||||
* @param Model $menu 생성된 메뉴
|
||||
*/
|
||||
public function handleMenuAfterCreate(Model $menu): void
|
||||
{
|
||||
@@ -532,8 +556,8 @@ class CoreActivityLogListener implements HookListenerInterface
|
||||
/**
|
||||
* 메뉴 수정 후 로그 기록
|
||||
*
|
||||
* @param Model $menu 수정된 메뉴
|
||||
* @param array|null $snapshot 수정 전 스냅샷
|
||||
* @param Model $menu 수정된 메뉴
|
||||
* @param array|null $snapshot 수정 전 스냅샷
|
||||
*/
|
||||
public function handleMenuAfterUpdate(Model $menu, ?array $snapshot = null): void
|
||||
{
|
||||
@@ -550,7 +574,7 @@ class CoreActivityLogListener implements HookListenerInterface
|
||||
/**
|
||||
* 메뉴 삭제 후 로그 기록
|
||||
*
|
||||
* @param int $menuId 삭제된 메뉴 ID
|
||||
* @param int $menuId 삭제된 메뉴 ID
|
||||
*/
|
||||
public function handleMenuAfterDelete(int $menuId): void
|
||||
{
|
||||
@@ -564,7 +588,7 @@ class CoreActivityLogListener implements HookListenerInterface
|
||||
/**
|
||||
* 메뉴 순서 변경 후 로그 기록
|
||||
*
|
||||
* @param array $orderData 순서 데이터
|
||||
* @param array $orderData 순서 데이터
|
||||
*/
|
||||
public function handleMenuAfterUpdateOrder(array $orderData): void
|
||||
{
|
||||
@@ -576,7 +600,7 @@ class CoreActivityLogListener implements HookListenerInterface
|
||||
/**
|
||||
* 메뉴 상태 전환 후 로그 기록
|
||||
*
|
||||
* @param Model $menu 메뉴
|
||||
* @param Model $menu 메뉴
|
||||
*/
|
||||
public function handleMenuAfterToggleStatus(Model $menu): void
|
||||
{
|
||||
@@ -590,9 +614,9 @@ class CoreActivityLogListener implements HookListenerInterface
|
||||
/**
|
||||
* 메뉴 역할 동기화 후 로그 기록
|
||||
*
|
||||
* @param Model $menu 메뉴
|
||||
* @param array $previousRoles 이전 역할 목록
|
||||
* @param array $currentRoles 현재 역할 목록
|
||||
* @param Model $menu 메뉴
|
||||
* @param array $previousRoles 이전 역할 목록
|
||||
* @param array $currentRoles 현재 역할 목록
|
||||
*/
|
||||
public function handleMenuAfterSyncRoles(Model $menu, array $previousRoles, array $currentRoles): void
|
||||
{
|
||||
@@ -614,9 +638,9 @@ class CoreActivityLogListener implements HookListenerInterface
|
||||
/**
|
||||
* 설정 저장 후 로그 기록
|
||||
*
|
||||
* @param string $tab 설정 탭
|
||||
* @param array $settings 저장된 설정
|
||||
* @param bool $result 저장 결과
|
||||
* @param string $tab 설정 탭
|
||||
* @param array $settings 저장된 설정
|
||||
* @param bool $result 저장 결과
|
||||
*/
|
||||
public function handleSettingsAfterSave(string $tab, array $settings, bool $result): void
|
||||
{
|
||||
@@ -629,9 +653,9 @@ class CoreActivityLogListener implements HookListenerInterface
|
||||
/**
|
||||
* 개별 설정 변경 후 로그 기록
|
||||
*
|
||||
* @param string $key 설정 키
|
||||
* @param mixed $value 설정 값
|
||||
* @param bool $result 저장 결과
|
||||
* @param string $key 설정 키
|
||||
* @param mixed $value 설정 값
|
||||
* @param bool $result 저장 결과
|
||||
*/
|
||||
public function handleSettingsAfterSet(string $key, mixed $value, bool $result): void
|
||||
{
|
||||
@@ -648,7 +672,7 @@ class CoreActivityLogListener implements HookListenerInterface
|
||||
/**
|
||||
* 스케줄 생성 후 로그 기록
|
||||
*
|
||||
* @param Model $schedule 생성된 스케줄
|
||||
* @param Model $schedule 생성된 스케줄
|
||||
*/
|
||||
public function handleScheduleAfterCreate(Model $schedule): void
|
||||
{
|
||||
@@ -662,8 +686,8 @@ class CoreActivityLogListener implements HookListenerInterface
|
||||
/**
|
||||
* 스케줄 수정 후 로그 기록
|
||||
*
|
||||
* @param Model $schedule 수정된 스케줄
|
||||
* @param array|null $snapshot 수정 전 스냅샷
|
||||
* @param Model $schedule 수정된 스케줄
|
||||
* @param array|null $snapshot 수정 전 스냅샷
|
||||
*/
|
||||
public function handleScheduleAfterUpdate(Model $schedule, ?array $snapshot = null): void
|
||||
{
|
||||
@@ -680,7 +704,7 @@ class CoreActivityLogListener implements HookListenerInterface
|
||||
/**
|
||||
* 스케줄 삭제 후 로그 기록
|
||||
*
|
||||
* @param int $scheduleId 삭제된 스케줄 ID
|
||||
* @param int $scheduleId 삭제된 스케줄 ID
|
||||
*/
|
||||
public function handleScheduleAfterDelete(int $scheduleId): void
|
||||
{
|
||||
@@ -694,8 +718,8 @@ class CoreActivityLogListener implements HookListenerInterface
|
||||
/**
|
||||
* 스케줄 수동 실행 후 로그 기록
|
||||
*
|
||||
* @param Model $schedule 실행된 스케줄
|
||||
* @param Model $history 실행 이력
|
||||
* @param Model $schedule 실행된 스케줄
|
||||
* @param Model $history 실행 이력
|
||||
*/
|
||||
public function handleScheduleAfterRun(Model $schedule, Model $history): void
|
||||
{
|
||||
@@ -709,10 +733,10 @@ class CoreActivityLogListener implements HookListenerInterface
|
||||
/**
|
||||
* 스케줄 일괄 상태 변경 후 로그 기록
|
||||
*
|
||||
* @param array $ids 대상 ID 목록
|
||||
* @param bool $isActive 활성화 여부
|
||||
* @param int $updatedCount 변경된 수
|
||||
* @param array $snapshots 변경 전 스냅샷 (id => snapshot)
|
||||
* @param array $ids 대상 ID 목록
|
||||
* @param bool $isActive 활성화 여부
|
||||
* @param int $updatedCount 변경된 수
|
||||
* @param array $snapshots 변경 전 스냅샷 (id => snapshot)
|
||||
*/
|
||||
public function handleScheduleAfterBulkUpdate(array $ids, bool $isActive, int $updatedCount, array $snapshots = []): void
|
||||
{
|
||||
@@ -740,9 +764,9 @@ class CoreActivityLogListener implements HookListenerInterface
|
||||
/**
|
||||
* 스케줄 일괄 삭제 후 로그 기록
|
||||
*
|
||||
* @param array $ids 대상 ID 목록
|
||||
* @param int $deletedCount 삭제된 수
|
||||
* @param array $snapshots 삭제 전 스냅샷 (id => snapshot)
|
||||
* @param array $ids 대상 ID 목록
|
||||
* @param int $deletedCount 삭제된 수
|
||||
* @param array $snapshots 삭제 전 스냅샷 (id => snapshot)
|
||||
*/
|
||||
public function handleScheduleAfterBulkDelete(array $ids, int $deletedCount, array $snapshots = []): void
|
||||
{
|
||||
@@ -769,7 +793,7 @@ class CoreActivityLogListener implements HookListenerInterface
|
||||
/**
|
||||
* 첨부파일 업로드 후 로그 기록
|
||||
*
|
||||
* @param Model $attachment 업로드된 첨부파일
|
||||
* @param Model $attachment 업로드된 첨부파일
|
||||
*/
|
||||
public function handleAttachmentAfterUpload(Model $attachment): void
|
||||
{
|
||||
@@ -782,7 +806,7 @@ class CoreActivityLogListener implements HookListenerInterface
|
||||
/**
|
||||
* 첨부파일 삭제 후 로그 기록
|
||||
*
|
||||
* @param Model|null $attachment 삭제된 첨부파일 (DispatchHookListenerJob 역직렬화 과정에서 null 가능)
|
||||
* @param Model|null $attachment 삭제된 첨부파일 (DispatchHookListenerJob 역직렬화 과정에서 null 가능)
|
||||
*/
|
||||
public function handleAttachmentAfterDelete(?Model $attachment = null): void
|
||||
{
|
||||
@@ -794,10 +818,10 @@ class CoreActivityLogListener implements HookListenerInterface
|
||||
/**
|
||||
* 첨부파일 일괄 삭제 후 로그 기록 (per-item)
|
||||
*
|
||||
* @param string $identifier 식별자
|
||||
* @param int $count 삭제된 수
|
||||
* @param array $ids 삭제된 첨부파일 ID 목록
|
||||
* @param array $snapshots 삭제 전 스냅샷 (keyBy id)
|
||||
* @param string $identifier 식별자
|
||||
* @param int $count 삭제된 수
|
||||
* @param array $ids 삭제된 첨부파일 ID 목록
|
||||
* @param array $snapshots 삭제 전 스냅샷 (keyBy id)
|
||||
*/
|
||||
public function handleAttachmentAfterBulkDelete(string $identifier, int $count, array $ids = [], array $snapshots = []): void
|
||||
{
|
||||
@@ -825,8 +849,8 @@ class CoreActivityLogListener implements HookListenerInterface
|
||||
/**
|
||||
* 모듈 설치 후 로그 기록
|
||||
*
|
||||
* @param string $moduleName 모듈 식별자
|
||||
* @param array $moduleInfo 모듈 정보
|
||||
* @param string $moduleName 모듈 식별자
|
||||
* @param array $moduleInfo 모듈 정보
|
||||
*/
|
||||
public function handleModuleAfterInstall(string $moduleName, array $moduleInfo): void
|
||||
{
|
||||
@@ -840,8 +864,8 @@ class CoreActivityLogListener implements HookListenerInterface
|
||||
/**
|
||||
* 모듈 활성화 후 로그 기록
|
||||
*
|
||||
* @param string $moduleName 모듈 식별자
|
||||
* @param array $moduleInfo 모듈 정보
|
||||
* @param string $moduleName 모듈 식별자
|
||||
* @param array $moduleInfo 모듈 정보
|
||||
*/
|
||||
public function handleModuleAfterActivate(string $moduleName, array $moduleInfo): void
|
||||
{
|
||||
@@ -854,7 +878,7 @@ class CoreActivityLogListener implements HookListenerInterface
|
||||
/**
|
||||
* 모듈 비활성화 후 로그 기록
|
||||
*
|
||||
* @param string $moduleName 모듈 식별자
|
||||
* @param string $moduleName 모듈 식별자
|
||||
*/
|
||||
public function handleModuleAfterDeactivate(string $moduleName): void
|
||||
{
|
||||
@@ -867,9 +891,9 @@ class CoreActivityLogListener implements HookListenerInterface
|
||||
/**
|
||||
* 모듈 제거 후 로그 기록
|
||||
*
|
||||
* @param string $moduleName 모듈 식별자
|
||||
* @param array $moduleInfo 모듈 정보
|
||||
* @param bool $deleteData 데이터 삭제 여부
|
||||
* @param string $moduleName 모듈 식별자
|
||||
* @param array $moduleInfo 모듈 정보
|
||||
* @param bool $deleteData 데이터 삭제 여부
|
||||
*/
|
||||
public function handleModuleAfterUninstall(string $moduleName, array $moduleInfo, bool $deleteData): void
|
||||
{
|
||||
@@ -883,9 +907,9 @@ class CoreActivityLogListener implements HookListenerInterface
|
||||
/**
|
||||
* 모듈 업데이트 후 로그 기록
|
||||
*
|
||||
* @param string $moduleName 모듈 식별자
|
||||
* @param array $result 업데이트 결과 배열 (['success' => bool, ...])
|
||||
* @param array $moduleInfo 모듈 정보
|
||||
* @param string $moduleName 모듈 식별자
|
||||
* @param array $result 업데이트 결과 배열 (['success' => bool, ...])
|
||||
* @param array $moduleInfo 모듈 정보
|
||||
*/
|
||||
public function handleModuleAfterUpdate(string $moduleName, array $result, array $moduleInfo): void
|
||||
{
|
||||
@@ -899,8 +923,8 @@ class CoreActivityLogListener implements HookListenerInterface
|
||||
/**
|
||||
* 모듈 레이아웃 갱신 후 로그 기록
|
||||
*
|
||||
* @param string $moduleName 모듈 식별자
|
||||
* @param array $result 갱신 결과
|
||||
* @param string $moduleName 모듈 식별자
|
||||
* @param array $result 갱신 결과
|
||||
*/
|
||||
public function handleModuleAfterRefreshLayouts(string $moduleName, array $result): void
|
||||
{
|
||||
@@ -917,8 +941,8 @@ class CoreActivityLogListener implements HookListenerInterface
|
||||
/**
|
||||
* 플러그인 설치 후 로그 기록
|
||||
*
|
||||
* @param string $pluginName 플러그인 식별자
|
||||
* @param array $pluginInfo 플러그인 정보
|
||||
* @param string $pluginName 플러그인 식별자
|
||||
* @param array $pluginInfo 플러그인 정보
|
||||
*/
|
||||
public function handlePluginAfterInstall(string $pluginName, array $pluginInfo): void
|
||||
{
|
||||
@@ -932,8 +956,8 @@ class CoreActivityLogListener implements HookListenerInterface
|
||||
/**
|
||||
* 플러그인 활성화 후 로그 기록
|
||||
*
|
||||
* @param string $pluginName 플러그인 식별자
|
||||
* @param array $pluginInfo 플러그인 정보
|
||||
* @param string $pluginName 플러그인 식별자
|
||||
* @param array $pluginInfo 플러그인 정보
|
||||
*/
|
||||
public function handlePluginAfterActivate(string $pluginName, array $pluginInfo): void
|
||||
{
|
||||
@@ -946,7 +970,7 @@ class CoreActivityLogListener implements HookListenerInterface
|
||||
/**
|
||||
* 플러그인 비활성화 후 로그 기록
|
||||
*
|
||||
* @param string $pluginName 플러그인 식별자
|
||||
* @param string $pluginName 플러그인 식별자
|
||||
*/
|
||||
public function handlePluginAfterDeactivate(string $pluginName): void
|
||||
{
|
||||
@@ -959,9 +983,9 @@ class CoreActivityLogListener implements HookListenerInterface
|
||||
/**
|
||||
* 플러그인 제거 후 로그 기록
|
||||
*
|
||||
* @param string $pluginName 플러그인 식별자
|
||||
* @param bool $deleteData 데이터 삭제 여부
|
||||
* @param bool $result 제거 결과
|
||||
* @param string $pluginName 플러그인 식별자
|
||||
* @param bool $deleteData 데이터 삭제 여부
|
||||
* @param bool $result 제거 결과
|
||||
*/
|
||||
public function handlePluginAfterUninstall(string $pluginName, bool $deleteData, bool $result): void
|
||||
{
|
||||
@@ -975,9 +999,9 @@ class CoreActivityLogListener implements HookListenerInterface
|
||||
/**
|
||||
* 플러그인 업데이트 후 로그 기록
|
||||
*
|
||||
* @param string $pluginName 플러그인 식별자
|
||||
* @param array $result 업데이트 결과 배열 (['success' => bool, ...])
|
||||
* @param array $pluginInfo 플러그인 정보
|
||||
* @param string $pluginName 플러그인 식별자
|
||||
* @param array $result 업데이트 결과 배열 (['success' => bool, ...])
|
||||
* @param array $pluginInfo 플러그인 정보
|
||||
*/
|
||||
public function handlePluginAfterUpdate(string $pluginName, array $result, array $pluginInfo): void
|
||||
{
|
||||
@@ -995,8 +1019,8 @@ class CoreActivityLogListener implements HookListenerInterface
|
||||
/**
|
||||
* 템플릿 설치 후 로그 기록
|
||||
*
|
||||
* @param string $identifier 템플릿 식별자
|
||||
* @param array $templateInfo 템플릿 정보
|
||||
* @param string $identifier 템플릿 식별자
|
||||
* @param array $templateInfo 템플릿 정보
|
||||
*/
|
||||
public function handleTemplateAfterInstall(string $identifier, array $templateInfo): void
|
||||
{
|
||||
@@ -1010,7 +1034,7 @@ class CoreActivityLogListener implements HookListenerInterface
|
||||
/**
|
||||
* 템플릿 활성화 후 로그 기록
|
||||
*
|
||||
* @param array $templateInfo 템플릿 정보
|
||||
* @param array $templateInfo 템플릿 정보
|
||||
*/
|
||||
public function handleTemplateAfterActivate(array $templateInfo): void
|
||||
{
|
||||
@@ -1023,7 +1047,7 @@ class CoreActivityLogListener implements HookListenerInterface
|
||||
/**
|
||||
* 템플릿 비활성화 후 로그 기록
|
||||
*
|
||||
* @param string $identifier 템플릿 식별자
|
||||
* @param string $identifier 템플릿 식별자
|
||||
*/
|
||||
public function handleTemplateAfterDeactivate(string $identifier): void
|
||||
{
|
||||
@@ -1036,9 +1060,9 @@ class CoreActivityLogListener implements HookListenerInterface
|
||||
/**
|
||||
* 템플릿 제거 후 로그 기록
|
||||
*
|
||||
* @param string $identifier 템플릿 식별자
|
||||
* @param array $templateInfo 템플릿 정보
|
||||
* @param bool $deleteData 데이터 삭제 여부
|
||||
* @param string $identifier 템플릿 식별자
|
||||
* @param array $templateInfo 템플릿 정보
|
||||
* @param bool $deleteData 데이터 삭제 여부
|
||||
*/
|
||||
public function handleTemplateAfterUninstall(string $identifier, array $templateInfo, bool $deleteData): void
|
||||
{
|
||||
@@ -1052,9 +1076,9 @@ class CoreActivityLogListener implements HookListenerInterface
|
||||
/**
|
||||
* 템플릿 버전 업데이트 후 로그 기록
|
||||
*
|
||||
* @param string $templateName 템플릿 식별자
|
||||
* @param array $result 업데이트 결과
|
||||
* @param array $templateInfo 템플릿 정보
|
||||
* @param string $templateName 템플릿 식별자
|
||||
* @param array $result 업데이트 결과
|
||||
* @param array $templateInfo 템플릿 정보
|
||||
*/
|
||||
public function handleTemplateAfterVersionUpdate(string $templateName, array $result, array $templateInfo): void
|
||||
{
|
||||
@@ -1068,8 +1092,8 @@ class CoreActivityLogListener implements HookListenerInterface
|
||||
/**
|
||||
* 템플릿 레이아웃 갱신 후 로그 기록
|
||||
*
|
||||
* @param string $identifier 템플릿 식별자
|
||||
* @param array $result 갱신 결과
|
||||
* @param string $identifier 템플릿 식별자
|
||||
* @param array $result 갱신 결과
|
||||
*/
|
||||
public function handleTemplateAfterRefreshLayouts(string $identifier, array $result): void
|
||||
{
|
||||
@@ -1086,10 +1110,10 @@ class CoreActivityLogListener implements HookListenerInterface
|
||||
/**
|
||||
* 레이아웃 수정 후 로그 기록
|
||||
*
|
||||
* @param Model $layout 수정된 레이아웃
|
||||
* @param int $templateId 템플릿 ID
|
||||
* @param string $name 레이아웃 이름
|
||||
* @param array $data 수정 데이터
|
||||
* @param Model $layout 수정된 레이아웃
|
||||
* @param int $templateId 템플릿 ID
|
||||
* @param string $name 레이아웃 이름
|
||||
* @param array $data 수정 데이터
|
||||
*/
|
||||
public function handleLayoutAfterUpdate(Model $layout, int $templateId, string $name, array $data): void
|
||||
{
|
||||
@@ -1103,10 +1127,10 @@ class CoreActivityLogListener implements HookListenerInterface
|
||||
/**
|
||||
* 레이아웃 버전 복원 후 로그 기록
|
||||
*
|
||||
* @param Model $newVersion 복원된 새 버전
|
||||
* @param int $templateId 템플릿 ID
|
||||
* @param string $name 레이아웃 이름
|
||||
* @param int $versionId 복원 대상 버전 ID
|
||||
* @param Model $newVersion 복원된 새 버전
|
||||
* @param int $templateId 템플릿 ID
|
||||
* @param string $name 레이아웃 이름
|
||||
* @param int $versionId 복원 대상 버전 ID
|
||||
*/
|
||||
public function handleLayoutAfterVersionRestore(Model $newVersion, int $templateId, string $name, int $versionId): void
|
||||
{
|
||||
@@ -1124,9 +1148,9 @@ class CoreActivityLogListener implements HookListenerInterface
|
||||
/**
|
||||
* 모듈 설정 저장 후 로그 기록
|
||||
*
|
||||
* @param string $identifier 모듈 식별자
|
||||
* @param array $settings 저장된 설정
|
||||
* @param bool $result 저장 결과
|
||||
* @param string $identifier 모듈 식별자
|
||||
* @param array $settings 저장된 설정
|
||||
* @param bool $result 저장 결과
|
||||
*/
|
||||
public function handleModuleSettingsAfterSave(string $identifier, array $settings, bool $result): void
|
||||
{
|
||||
@@ -1140,7 +1164,7 @@ class CoreActivityLogListener implements HookListenerInterface
|
||||
/**
|
||||
* 모듈 설정 초기화 후 로그 기록
|
||||
*
|
||||
* @param string $identifier 모듈 식별자
|
||||
* @param string $identifier 모듈 식별자
|
||||
*/
|
||||
public function handleModuleSettingsAfterReset(string $identifier): void
|
||||
{
|
||||
@@ -1157,9 +1181,9 @@ class CoreActivityLogListener implements HookListenerInterface
|
||||
/**
|
||||
* 플러그인 설정 저장 후 로그 기록
|
||||
*
|
||||
* @param string $identifier 플러그인 식별자
|
||||
* @param array $settings 저장된 설정
|
||||
* @param bool $result 저장 결과
|
||||
* @param string $identifier 플러그인 식별자
|
||||
* @param array $settings 저장된 설정
|
||||
* @param bool $result 저장 결과
|
||||
*/
|
||||
public function handlePluginSettingsAfterSave(string $identifier, array $settings, bool $result): void
|
||||
{
|
||||
@@ -1173,7 +1197,7 @@ class CoreActivityLogListener implements HookListenerInterface
|
||||
/**
|
||||
* 플러그인 설정 초기화 후 로그 기록
|
||||
*
|
||||
* @param string $identifier 플러그인 식별자
|
||||
* @param string $identifier 플러그인 식별자
|
||||
*/
|
||||
public function handlePluginSettingsAfterReset(string $identifier): void
|
||||
{
|
||||
@@ -1190,10 +1214,10 @@ class CoreActivityLogListener implements HookListenerInterface
|
||||
/**
|
||||
* 본인인증 challenge 요청 후 로그 기록.
|
||||
*
|
||||
* @param \App\Extension\IdentityVerification\DTO\VerificationChallenge $challenge
|
||||
* @param string $purpose
|
||||
* @param \App\Models\User|array $target
|
||||
* @param array $context
|
||||
* @param VerificationChallenge $challenge 발급된 본인인증 challenge
|
||||
* @param string $purpose 인증 목적 (IdentityVerificationPurpose 값)
|
||||
* @param User|array $target 인증 대상 (회원 모델 또는 이메일/전화 배열)
|
||||
* @param array $context 부가 컨텍스트 (IP 등)
|
||||
*/
|
||||
public function handleIdentityRequested($challenge, string $purpose, $target, array $context = []): void
|
||||
{
|
||||
@@ -1213,9 +1237,9 @@ class CoreActivityLogListener implements HookListenerInterface
|
||||
/**
|
||||
* 본인인증 검증 후 로그 기록 (성공·실패 공통 디스패치).
|
||||
*
|
||||
* @param \App\Extension\IdentityVerification\DTO\VerificationResult $result
|
||||
* @param \App\Models\IdentityVerificationLog|null $log
|
||||
* @param array $context
|
||||
* @param VerificationResult $result 검증 결과 DTO
|
||||
* @param IdentityVerificationLog|null $log 검증 로그 (없을 수 있음)
|
||||
* @param array $context 부가 컨텍스트 (IP 등)
|
||||
*/
|
||||
public function handleIdentityVerified($result, $log, array $context = []): void
|
||||
{
|
||||
@@ -1238,7 +1262,7 @@ class CoreActivityLogListener implements HookListenerInterface
|
||||
/**
|
||||
* 본인인증 challenge 만료 로그 기록.
|
||||
*
|
||||
* @param \App\Models\IdentityVerificationLog $log
|
||||
* @param IdentityVerificationLog $log
|
||||
*/
|
||||
public function handleIdentityExpired($log): void
|
||||
{
|
||||
@@ -1251,5 +1275,4 @@ class CoreActivityLogListener implements HookListenerInterface
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -90,9 +90,13 @@ class EnforceIdentityPolicyListener implements HookListenerInterface
|
||||
// 2) 코어 hook 은 getSubscribedHooks() 가 소유하므로 동적 등록 대상에서 제외
|
||||
$coreHooks = array_fill_keys(static::coreHookTargets(), true);
|
||||
|
||||
// 3) 현재 hook scope 정책 target 으로 재구독
|
||||
// 3) 전담 리스너가 소유하는 target 은 일반 enforce 대상에서 제외
|
||||
$delegated = array_fill_keys(static::delegatedHookTargets(), true);
|
||||
|
||||
// 4) 현재 hook scope 정책 target 으로 재구독
|
||||
foreach (static::loadDynamicHookTargets() as $hookName) {
|
||||
if (! is_string($hookName) || $hookName === '' || isset($coreHooks[$hookName])) {
|
||||
if (! is_string($hookName) || $hookName === ''
|
||||
|| isset($coreHooks[$hookName]) || isset($delegated[$hookName])) {
|
||||
continue;
|
||||
}
|
||||
if (isset(self::$dynamicCallbacks[$hookName])) {
|
||||
@@ -145,6 +149,27 @@ class EnforceIdentityPolicyListener implements HookListenerInterface
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 전담 리스너가 강제를 소유하는 hook target 목록.
|
||||
*
|
||||
* 이 리스너는 "행위 직전(before_*)" 훅을 막아 세우는 가드다. 행위가 이미 끝난 뒤 발화하는
|
||||
* 훅에서 예외를 던지면 되돌릴 것이 없는 상태에서 응답만 깨진다.
|
||||
*
|
||||
* `core.auth.after_register` 가 그 경우다. 이 훅은 `InitiateIdentityChallengeAfterRegister`
|
||||
* 가 소유하며, `core.auth.signup_after_create` 정책이 켜져 있으면 계정을 '인증 대기' 로 두고
|
||||
* 본인확인 challenge 를 발행한다(가입 자체는 성립). 여기서 다시 enforce 하면 가입이 428 로
|
||||
* 막혀 '가입 전 본인확인'(`core.auth.signup_before_submit`) 정책과 동작이 같아지고,
|
||||
* '가입 후' 정책은 켜는 순간 아무도 가입할 수 없게 된다.
|
||||
*
|
||||
* @return list<string> 전담 소유 hook target 목록
|
||||
*/
|
||||
protected static function delegatedHookTargets(): array
|
||||
{
|
||||
return [
|
||||
'core.auth.after_register',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* identity_policies 테이블에서 scope='hook' 정책의 target 목록을 추출합니다.
|
||||
*
|
||||
@@ -175,6 +200,12 @@ class EnforceIdentityPolicyListener implements HookListenerInterface
|
||||
return;
|
||||
}
|
||||
|
||||
// 전담 리스너가 소유하는 훅은 구독 단계에서 제외되지만, 다른 경로로 호출되더라도
|
||||
// 이중 강제가 생기지 않도록 여기서도 막는다 (delegatedHookTargets 주석 참조).
|
||||
if (in_array($hookName, static::delegatedHookTargets(), true)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$policies = $this->policyRepository->resolveByScopeTarget('hook', $hookName);
|
||||
if ($policies->isEmpty()) {
|
||||
return;
|
||||
|
||||
@@ -47,7 +47,7 @@ class HandleFailedLoginListener implements HookListenerInterface
|
||||
* 로그인 실패 시 카운트 증가 및 임계 도달 시 잠금 처리.
|
||||
*
|
||||
* @param string $email 실패한 로그인 이메일
|
||||
* @param array $context IP/UA/시각 등 부가 정보
|
||||
* @param array $context IP/UA/시각 등 부가 정보
|
||||
*/
|
||||
public function handleFailed(string $email, array $context = []): void
|
||||
{
|
||||
@@ -79,12 +79,14 @@ class HandleFailedLoginListener implements HookListenerInterface
|
||||
$user
|
||||
);
|
||||
|
||||
// 잠금 시간 0(= 무한대) 은 영구 잠금이라 해제 시각이 null 이다.
|
||||
$lockedUntil = $this->userRepository->lockAccount($user, $lockoutMinutes);
|
||||
|
||||
HookManager::doAction('core.auth.account_locked', $user, array_merge($context, [
|
||||
'attempts' => $newCount,
|
||||
'locked_until' => $lockedUntil,
|
||||
'lockout_minutes' => $lockoutMinutes,
|
||||
'permanent' => $lockedUntil === null,
|
||||
]));
|
||||
}
|
||||
}
|
||||
+12
-9
@@ -3,24 +3,25 @@
|
||||
namespace App\Models;
|
||||
|
||||
// use Illuminate\Contracts\Auth\MustVerifyEmail;
|
||||
use App\Contracts\UniqueIdServiceInterface;
|
||||
use App\Enums\MenuPermissionType;
|
||||
use App\Enums\PermissionType;
|
||||
use App\Enums\ScopeType;
|
||||
use App\Enums\UserStatus;
|
||||
use Database\Factories\UserFactory;
|
||||
use Illuminate\Contracts\Translation\HasLocalePreference;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
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 App\Contracts\UniqueIdServiceInterface;
|
||||
use Illuminate\Contracts\Translation\HasLocalePreference;
|
||||
use Illuminate\Foundation\Auth\User as Authenticatable;
|
||||
use Illuminate\Notifications\Notifiable;
|
||||
use Laravel\Sanctum\HasApiTokens;
|
||||
|
||||
class User extends Authenticatable implements HasLocalePreference
|
||||
{
|
||||
/** @use HasFactory<\Database\Factories\UserFactory> */
|
||||
/** @use HasFactory<UserFactory> */
|
||||
use HasApiTokens, HasFactory, Notifiable;
|
||||
|
||||
/** @var array<string, array> 활동 로그 추적 필드 */
|
||||
@@ -31,7 +32,7 @@ class User extends Authenticatable implements HasLocalePreference
|
||||
'language' => ['label_key' => 'activity_log.fields.language', 'type' => 'text'],
|
||||
'timezone' => ['label_key' => 'activity_log.fields.timezone', 'type' => 'text'],
|
||||
'country' => ['label_key' => 'activity_log.fields.country', 'type' => 'text'],
|
||||
'status' => ['label_key' => 'activity_log.fields.status', 'type' => 'enum', 'enum' => \App\Enums\UserStatus::class],
|
||||
'status' => ['label_key' => 'activity_log.fields.status', 'type' => 'enum', 'enum' => UserStatus::class],
|
||||
'is_super' => ['label_key' => 'activity_log.fields.is_super', 'type' => 'boolean'],
|
||||
'homepage' => ['label_key' => 'activity_log.fields.homepage', 'type' => 'text'],
|
||||
'mobile' => ['label_key' => 'activity_log.fields.mobile', 'type' => 'text'],
|
||||
@@ -108,6 +109,7 @@ class User extends Authenticatable implements HasLocalePreference
|
||||
'mobile_verified_at',
|
||||
'failed_login_attempts',
|
||||
'locked_until',
|
||||
'locked_permanently',
|
||||
'last_failed_login_at',
|
||||
];
|
||||
|
||||
@@ -140,6 +142,7 @@ class User extends Authenticatable implements HasLocalePreference
|
||||
'is_super' => 'boolean',
|
||||
'failed_login_attempts' => 'integer',
|
||||
'locked_until' => 'datetime',
|
||||
'locked_permanently' => 'boolean',
|
||||
'last_failed_login_at' => 'datetime',
|
||||
];
|
||||
}
|
||||
@@ -196,7 +199,7 @@ class User extends Authenticatable implements HasLocalePreference
|
||||
/**
|
||||
* 사용자가 생성한 모듈들과의 관계를 정의합니다.
|
||||
*
|
||||
* @return \Illuminate\Database\Eloquent\Relations\HasMany
|
||||
* @return HasMany
|
||||
*/
|
||||
public function modules()
|
||||
{
|
||||
@@ -206,7 +209,7 @@ class User extends Authenticatable implements HasLocalePreference
|
||||
/**
|
||||
* 사용자가 생성한 플러그인들과의 관계를 정의합니다.
|
||||
*
|
||||
* @return \Illuminate\Database\Eloquent\Relations\HasMany
|
||||
* @return HasMany
|
||||
*/
|
||||
public function plugins()
|
||||
{
|
||||
@@ -388,8 +391,8 @@ class User extends Authenticatable implements HasLocalePreference
|
||||
/**
|
||||
* 슈퍼 관리자만 조회합니다.
|
||||
*
|
||||
* @param \Illuminate\Database\Eloquent\Builder $query
|
||||
* @return \Illuminate\Database\Eloquent\Builder
|
||||
* @param Builder $query
|
||||
* @return Builder
|
||||
*/
|
||||
public function scopeSuperAdmins($query)
|
||||
{
|
||||
@@ -445,7 +448,7 @@ class User extends Authenticatable implements HasLocalePreference
|
||||
/**
|
||||
* 사용자가 생성한 메뉴들과의 관계를 정의합니다.
|
||||
*
|
||||
* @return \Illuminate\Database\Eloquent\Relations\HasMany
|
||||
* @return HasMany
|
||||
*/
|
||||
public function menus()
|
||||
{
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
namespace App\Providers;
|
||||
|
||||
use App\Repositories\JsonConfigRepository;
|
||||
use App\Support\AllowedExtensions;
|
||||
use Illuminate\Support\Facades\Config;
|
||||
use Illuminate\Support\ServiceProvider;
|
||||
|
||||
@@ -652,12 +653,19 @@ class SettingsServiceProvider extends ServiceProvider
|
||||
Config::set('filesystems.default', $uploadSettings['disk']);
|
||||
}
|
||||
|
||||
if (! empty($uploadSettings['max_size'])) {
|
||||
Config::set('g7.upload.max_size', (int) $uploadSettings['max_size']);
|
||||
// 관리자 설정은 MB, config/attachment.* 는 KB — 변환은 이 지점 단 한 곳에서만 수행한다.
|
||||
// (기존에는 존재하지 않는 키 `max_size` 를 읽어 설정이 어디에도 반영되지 않았다)
|
||||
if (! empty($uploadSettings['max_file_size'])) {
|
||||
Config::set('attachment.max_file_size', (int) $uploadSettings['max_file_size'] * 1024);
|
||||
}
|
||||
|
||||
if (! empty($uploadSettings['allowed_extensions'])) {
|
||||
Config::set('g7.upload.allowed_extensions', $uploadSettings['allowed_extensions']);
|
||||
// 화면은 콤마 문자열을 보내고 API 직접 호출은 배열을 보낸다. 배열만 받아들이면
|
||||
// 문자열로 저장된 설정이 조용히 버려져 관리자가 확장자를 바꿔도 반영되지 않는다.
|
||||
if (isset($uploadSettings['allowed_extensions'])) {
|
||||
Config::set(
|
||||
'attachment.allowed_extensions',
|
||||
AllowedExtensions::normalize($uploadSettings['allowed_extensions'])
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,7 @@ use Illuminate\Contracts\Pagination\LengthAwarePaginator;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\Collection;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Laravel\Sanctum\PersonalAccessToken;
|
||||
|
||||
class UserRepository implements UserRepositoryInterface
|
||||
{
|
||||
@@ -294,16 +295,22 @@ class UserRepository implements UserRepositoryInterface
|
||||
/**
|
||||
* 사용자의 계정을 지정된 분만큼 잠급니다.
|
||||
*
|
||||
* `$minutes <= 0` 은 보안 환경설정의 "0 = 무한대" 규약에 따라 영구 잠금으로 처리합니다.
|
||||
* 영구 잠금은 해제 시각이 없으므로 `locked_until` 을 NULL 로 두고
|
||||
* `locked_permanently` 플래그로 상태를 표현합니다 (NULL 은 이미 "잠금 없음" 을 의미).
|
||||
*
|
||||
* @param User $user 잠글 사용자
|
||||
* @param int $minutes 잠금 유지 시간(분)
|
||||
* @return Carbon 잠금 해제 시각
|
||||
* @param int $minutes 잠금 유지 시간(분). 0 이하는 무기한
|
||||
* @return Carbon|null 잠금 해제 시각 (영구 잠금은 null)
|
||||
*/
|
||||
public function lockAccount(User $user, int $minutes): Carbon
|
||||
public function lockAccount(User $user, int $minutes): ?Carbon
|
||||
{
|
||||
$lockedUntil = now()->addMinutes(max(1, $minutes));
|
||||
$permanent = $minutes <= 0;
|
||||
$lockedUntil = $permanent ? null : now()->addMinutes($minutes);
|
||||
|
||||
$user->forceFill([
|
||||
'locked_until' => $lockedUntil,
|
||||
'locked_permanently' => $permanent,
|
||||
'failed_login_attempts' => 0,
|
||||
])->save();
|
||||
|
||||
@@ -321,15 +328,18 @@ class UserRepository implements UserRepositoryInterface
|
||||
{
|
||||
$needsReset = ($user->failed_login_attempts ?? 0) > 0
|
||||
|| $user->locked_until !== null
|
||||
|| (bool) $user->locked_permanently
|
||||
|| $user->last_failed_login_at !== null;
|
||||
|
||||
if (! $needsReset) {
|
||||
return;
|
||||
}
|
||||
|
||||
// locked_permanently 를 빠뜨리면 성공 로그인·관리자 해제 후에도 영구 잠금이 잔존한다.
|
||||
$user->forceFill([
|
||||
'failed_login_attempts' => 0,
|
||||
'locked_until' => null,
|
||||
'locked_permanently' => false,
|
||||
'last_failed_login_at' => null,
|
||||
])->save();
|
||||
}
|
||||
@@ -342,10 +352,74 @@ class UserRepository implements UserRepositoryInterface
|
||||
*/
|
||||
public function isLocked(User $user): bool
|
||||
{
|
||||
// 영구 잠금 판정이 먼저 — 해제 시각이 없으므로 NULL 체크에 먼저 걸리면 안 된다.
|
||||
if ((bool) $user->locked_permanently) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if ($user->locked_until === null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return $user->locked_until->isFuture();
|
||||
}
|
||||
|
||||
/**
|
||||
* UUID 로 사용자를 찾습니다.
|
||||
*
|
||||
* @param string $uuid 사용자 UUID
|
||||
* @return User|null 찾은 사용자 모델 또는 null
|
||||
*/
|
||||
public function findByUuid(string $uuid): ?User
|
||||
{
|
||||
return User::where('uuid', $uuid)->first();
|
||||
}
|
||||
|
||||
/**
|
||||
* UUID 목록에 해당하는 사용자의 정수 ID 배열을 반환합니다.
|
||||
*
|
||||
* @param array $uuids 사용자 UUID 배열
|
||||
* @return array<int, int> 사용자 ID 배열
|
||||
*/
|
||||
public function getIdsByUuids(array $uuids): array
|
||||
{
|
||||
if (empty($uuids)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return User::whereIn('uuid', $uuids)->pluck('id')->all();
|
||||
}
|
||||
|
||||
/**
|
||||
* 사용자 ID 목록의 지정 컬럼을 일괄 갱신합니다.
|
||||
*
|
||||
* @param array $ids 사용자 ID 배열
|
||||
* @param array $data 갱신할 컬럼 값
|
||||
* @return int 갱신된 행 수
|
||||
*/
|
||||
public function updateManyByIds(array $ids, array $data): int
|
||||
{
|
||||
if (empty($ids)) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
return User::whereIn('id', $ids)->update($data);
|
||||
}
|
||||
|
||||
/**
|
||||
* 사용자 ID 목록의 인증 토큰을 모두 삭제합니다.
|
||||
*
|
||||
* @param array $ids 사용자 ID 배열
|
||||
* @return int 삭제된 토큰 수
|
||||
*/
|
||||
public function deleteTokensByUserIds(array $ids): int
|
||||
{
|
||||
if (empty($ids)) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
return PersonalAccessToken::where('tokenable_type', User::class)
|
||||
->whereIn('tokenable_id', $ids)
|
||||
->delete();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
<?php
|
||||
|
||||
namespace App\Rules;
|
||||
|
||||
use Illuminate\Validation\Rules\Password;
|
||||
|
||||
/**
|
||||
* 비밀번호 정책 팩토리
|
||||
*
|
||||
* 보안 환경설정(`security.password_min_length`, `security.require_password_special_char`)을
|
||||
* 실제 검증 규칙으로 변환합니다.
|
||||
*
|
||||
* 기존에는 7개 FormRequest 가 각자 `min:8` / `min:6` 리터럴을 들고 있어 값이 서로 어긋났고,
|
||||
* 관리자가 설정한 정책은 어디에도 적용되지 않는 완전 고아였습니다.
|
||||
*
|
||||
* 로그인(`LoginRequest`)에는 적용하지 않습니다 — 로그인은 기존 비밀번호를 *대조* 하는
|
||||
* 행위이지 새 정책을 강제하는 지점이 아닙니다. 정책을 올리면 기존 사용자가 자기 계정에
|
||||
* 접근조차 못 하고 재설정 흐름도 로그인 뒤에 있어 데드락이 되며, 길이 규칙은 미인증
|
||||
* 공격자에게 "이 비밀번호는 정책 미달" 이라는 사실을 누설합니다.
|
||||
*/
|
||||
class PasswordPolicy
|
||||
{
|
||||
/**
|
||||
* 기본 최소 길이 (설정 미지정 시)
|
||||
*/
|
||||
public const DEFAULT_MIN_LENGTH = 8;
|
||||
|
||||
/**
|
||||
* 현재 보안 설정을 반영한 비밀번호 규칙을 반환합니다.
|
||||
*
|
||||
* @return Password 비밀번호 검증 규칙
|
||||
*/
|
||||
public static function rule(): Password
|
||||
{
|
||||
$minLength = (int) g7_core_settings('security.password_min_length', self::DEFAULT_MIN_LENGTH);
|
||||
$minLength = $minLength > 0 ? $minLength : self::DEFAULT_MIN_LENGTH;
|
||||
|
||||
$rule = Password::min($minLength);
|
||||
|
||||
if ((bool) g7_core_settings('security.require_password_special_char', false)) {
|
||||
$rule = $rule->symbols();
|
||||
}
|
||||
|
||||
return $rule;
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,7 @@ use App\Contracts\Repositories\AttachmentRepositoryInterface;
|
||||
use App\Enums\AttachmentSourceType;
|
||||
use App\Extension\HookManager;
|
||||
use App\Models\Attachment;
|
||||
use App\Models\User;
|
||||
use Illuminate\Auth\Access\AuthorizationException;
|
||||
use Illuminate\Http\UploadedFile;
|
||||
use Illuminate\Support\Collection;
|
||||
@@ -58,8 +59,11 @@ class AttachmentService
|
||||
// 필터 훅 - 파일 데이터 변형 (압축, 리사이즈 등 확장 포인트)
|
||||
$file = HookManager::applyFilters('core.attachment.filter_upload_file', $file);
|
||||
|
||||
// 저장 경로 생성 (날짜별 디렉토리)
|
||||
$storedFilename = Str::uuid().'.'.$file->getClientOriginalExtension();
|
||||
// 저장 경로 생성 (날짜별 디렉토리).
|
||||
// 확장자는 클라이언트가 보낸 파일명이 아니라 MIME 추론값을 우선 사용한다 —
|
||||
// 파일명 확장자는 사용자가 임의로 바꿀 수 있어 저장 확장자의 근거가 될 수 없다.
|
||||
$extension = strtolower($file->extension() ?: $file->getClientOriginalExtension());
|
||||
$storedFilename = Str::uuid().($extension !== '' ? '.'.$extension : '');
|
||||
$datePath = date('Y/m/d');
|
||||
$path = "{$datePath}/{$storedFilename}";
|
||||
|
||||
@@ -217,7 +221,7 @@ class AttachmentService
|
||||
* 기능 레벨 권한 체크 (permission_hooks) - 다운로드 기능 자체에 대한 접근 권한
|
||||
*
|
||||
* @param string $hash 첨부파일 해시
|
||||
* @param \App\Models\User|null $user 요청한 사용자 (null이면 비로그인)
|
||||
* @param User|null $user 요청한 사용자 (null이면 비로그인)
|
||||
* @return StreamedResponse|null 다운로드 응답 또는 null
|
||||
*
|
||||
* @throws AuthorizationException 기능 레벨 권한이 없는 경우
|
||||
@@ -263,7 +267,7 @@ class AttachmentService
|
||||
* 컨트롤러에서 fileResponse()로 캐싱 헤더와 함께 응답할 수 있습니다.
|
||||
*
|
||||
* @param string $hash 첨부파일 해시
|
||||
* @param \App\Models\User|null $user 요청한 사용자 (null이면 비로그인)
|
||||
* @param User|null $user 요청한 사용자 (null이면 비로그인)
|
||||
* @return array{path: string, mime_type: string, filename: string}|null 파일 정보 또는 null
|
||||
*
|
||||
* @throws AuthorizationException 기능 레벨 권한이 없는 경우
|
||||
|
||||
@@ -99,7 +99,11 @@ class AuthService
|
||||
if ((bool) g7_core_settings('security.login_attempt_enabled', true)) {
|
||||
$candidate = $this->userRepository->findByEmail($email);
|
||||
if ($candidate !== null && $this->userRepository->isLocked($candidate)) {
|
||||
$remaining = max(1, (int) ceil(now()->diffInSeconds($candidate->locked_until, false) / 60));
|
||||
// 영구 잠금은 해제 시각이 없다 — diffInSeconds(null) 로 폭발하지 않도록 분기.
|
||||
$remaining = $candidate->locked_until === null
|
||||
? null
|
||||
: max(1, (int) ceil(now()->diffInSeconds($candidate->locked_until, false) / 60));
|
||||
|
||||
throw new AccountLockedException(
|
||||
lockedUntil: $candidate->locked_until,
|
||||
remainingMinutes: $remaining,
|
||||
|
||||
@@ -182,6 +182,7 @@ class IdentityVerificationService
|
||||
*
|
||||
* @param string $challengeId Challenge UUID
|
||||
* @return array<string, mixed>|null 공개 상태 또는 null (없는 경우)
|
||||
*
|
||||
* @since engine-v1.46.0
|
||||
*/
|
||||
public function getStatus(string $challengeId): ?array
|
||||
@@ -205,7 +206,9 @@ class IdentityVerificationService
|
||||
'purpose' => $log->purpose,
|
||||
'render_hint' => $log->render_hint,
|
||||
'expires_at' => optional($log->expires_at)->toIso8601String(),
|
||||
'attempts' => (int) $log->attempts,
|
||||
// 시도 횟수(attempts)는 공개 폴링 응답에 싣지 않는다 — challenge id 만 알면 누구나
|
||||
// 조회할 수 있는 경로라, 남의 인증 시도가 몇 번 실패했는지가 그대로 드러난다.
|
||||
// 화면의 '남은 시도 횟수' 는 모달이 자기 시도를 세어 표시하므로 영향이 없다.
|
||||
'max_attempts' => (int) $log->max_attempts,
|
||||
'public_payload' => $publicPayload,
|
||||
];
|
||||
@@ -222,6 +225,7 @@ class IdentityVerificationService
|
||||
* @param array<string, mixed> $input provider 가 보낸 페이로드 (code/token/state 등)
|
||||
* @param array<string, mixed> $context origin 정보 (origin_type=callback)
|
||||
* @return VerificationResult provider 의 검증 결과 (challenge mismatch 시 failure)
|
||||
*
|
||||
* @since engine-v1.46.0
|
||||
*/
|
||||
public function handleProviderCallback(string $providerId, string $challengeId, array $input, array $context = []): VerificationResult
|
||||
|
||||
@@ -24,6 +24,11 @@ class TemplateService
|
||||
{
|
||||
use ResolvesLanguageFragments;
|
||||
|
||||
/**
|
||||
* 직전 라우트 병합에서 활성 모듈 디렉토리가 비어 라우트가 누락됐는지 여부
|
||||
*/
|
||||
private bool $routeMergeDegraded = false;
|
||||
|
||||
public function __construct(
|
||||
private TemplateRepositoryInterface $templateRepository,
|
||||
private TemplateManagerInterface $templateManager,
|
||||
@@ -1074,6 +1079,8 @@ class TemplateService
|
||||
*/
|
||||
public function getRoutesDataWithModules(string $identifier): array
|
||||
{
|
||||
$this->routeMergeDegraded = false;
|
||||
|
||||
// 1. 템플릿 DB 조회 및 활성화 여부 확인
|
||||
$template = $this->templateRepository->findByIdentifier($identifier);
|
||||
if (! $template || $template->status !== ExtensionStatus::Active->value) {
|
||||
@@ -1172,9 +1179,22 @@ class TemplateService
|
||||
'success' => true,
|
||||
'data' => $resultData,
|
||||
'error' => null,
|
||||
'degraded' => $this->routeMergeDegraded,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 직전 라우트 병합이 열화 상태였는지 여부를 반환합니다.
|
||||
*
|
||||
* 활성 모듈의 디렉토리가 없어 그 모듈 라우트가 통째로 빠진 경우 true.
|
||||
*
|
||||
* @return bool 열화 여부
|
||||
*/
|
||||
public function lastRouteMergeWasDegraded(): bool
|
||||
{
|
||||
return $this->routeMergeDegraded;
|
||||
}
|
||||
|
||||
/**
|
||||
* 레이아웃 편집기용 routes 데이터를 source 태깅과 함께 반환합니다.
|
||||
*
|
||||
@@ -1653,6 +1673,15 @@ class TemplateService
|
||||
}
|
||||
|
||||
if ($routesFilePath === null) {
|
||||
// 활성 모듈의 디렉토리 자체가 없다면 업데이트 중 활성 디렉토리가 잠시 비운
|
||||
// 상태다(정상적으로 admin 라우트가 없는 모듈과 구분된다). 이때의 병합 결과는
|
||||
// 그 모듈의 화면이 통째로 빠진 열화 스냅샷이므로 호출자가 캐시하지 않도록
|
||||
// 표시한다. 표시 없이 캐시되면 업데이트가 끝난 뒤에도 캐시가 만료될 때까지
|
||||
// 해당 모듈의 모든 화면이 404 로 남는다.
|
||||
if (! is_dir(base_path("modules/{$moduleIdentifier}"))) {
|
||||
$this->routeMergeDegraded = true;
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
|
||||
@@ -2,18 +2,17 @@
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Contracts\Repositories\RoleRepositoryInterface;
|
||||
use App\Contracts\Repositories\UserRepositoryInterface;
|
||||
use App\Enums\UserStatus;
|
||||
use App\Exceptions\CannotDeleteSuperAdminException;
|
||||
use App\Extension\HookManager;
|
||||
use App\Helpers\PermissionHelper;
|
||||
use App\Models\ActivityLog;
|
||||
use App\Helpers\TimezoneHelper;
|
||||
use App\Models\Role;
|
||||
use App\Models\ActivityLog;
|
||||
use App\Models\User;
|
||||
use Exception;
|
||||
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
|
||||
use Laravel\Sanctum\PersonalAccessToken;
|
||||
use Illuminate\Database\Eloquent\Collection;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
@@ -24,6 +23,7 @@ class UserService
|
||||
{
|
||||
public function __construct(
|
||||
private UserRepositoryInterface $userRepository,
|
||||
private RoleRepositoryInterface $roleRepository,
|
||||
private AttachmentService $attachmentService
|
||||
) {}
|
||||
|
||||
@@ -79,7 +79,7 @@ class UserService
|
||||
|
||||
// 역할 할당 권한 체크: core.permissions.update 권한 없으면 기본 역할 자동 할당
|
||||
if (! PermissionHelper::check('core.permissions.update')) {
|
||||
$defaultRoleId = Role::where('identifier', 'user')->value('id');
|
||||
$defaultRoleId = $this->roleRepository->findByIdentifier('user')?->id;
|
||||
$roleIds = $defaultRoleId ? [$defaultRoleId] : null;
|
||||
}
|
||||
|
||||
@@ -156,7 +156,7 @@ class UserService
|
||||
|
||||
// 자기잠금 방지: 마지막 admin 역할 사용자가 자기 admin 역할을 제거하려는 경우 차단
|
||||
if ($roleIds !== null && $authUser && $authUser->id === $user->id) {
|
||||
$adminRole = Role::where('identifier', 'admin')->first();
|
||||
$adminRole = $this->roleRepository->findByIdentifier('admin');
|
||||
if ($adminRole && $user->roles->contains('id', $adminRole->id) && ! in_array($adminRole->id, $roleIds)) {
|
||||
// admin 역할을 가진 다른 사용자가 있는지 확인
|
||||
$otherAdminCount = $adminRole->users()->where('users.id', '!=', $user->id)->count();
|
||||
@@ -372,7 +372,7 @@ class UserService
|
||||
*/
|
||||
public function getUserByUuid(string $uuid): ?User
|
||||
{
|
||||
$user = User::where('uuid', $uuid)->first();
|
||||
$user = $this->userRepository->findByUuid($uuid);
|
||||
|
||||
if ($user) {
|
||||
HookManager::doAction('core.user.after_show', $user);
|
||||
@@ -486,9 +486,9 @@ class UserService
|
||||
/**
|
||||
* 사용자의 활동 로그를 조회합니다.
|
||||
*
|
||||
* @param int $userId 사용자 ID
|
||||
* @param int $limit 조회 건수
|
||||
* @return \Illuminate\Support\Collection
|
||||
* @param int $userId 사용자 ID
|
||||
* @param int $limit 조회 건수
|
||||
* @return \Illuminate\Support\Collection 활동 로그 요약 컬렉션
|
||||
*/
|
||||
public function getUserActivityLogs(int $userId, int $limit = 50): \Illuminate\Support\Collection
|
||||
{
|
||||
@@ -506,6 +506,31 @@ class UserService
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 사용자의 계정 잠금을 해제합니다 (관리자 수동 해제).
|
||||
*
|
||||
* 로그인 시도 추적 컬럼을 모두 초기화합니다. 영구 잠금(`locked_permanently`)도 함께
|
||||
* 해제되며, 이 경로가 없으면 잠금 시간 0(무한대) 으로 잠긴 계정은 성공 로그인 자체가
|
||||
* 불가하므로 DB 직접 조작 외에 복구 수단이 없습니다.
|
||||
*
|
||||
* @param User $user 잠금을 해제할 사용자
|
||||
* @return User 갱신된 사용자 모델
|
||||
*/
|
||||
public function unlockAccount(User $user): User
|
||||
{
|
||||
HookManager::doAction('core.user.before_unlock', $user);
|
||||
|
||||
$this->userRepository->resetLoginAttempts($user);
|
||||
|
||||
$user = $user->fresh();
|
||||
|
||||
HookManager::doAction('core.auth.account_unlocked', $user, [
|
||||
'ip_address' => request()->ip(),
|
||||
]);
|
||||
|
||||
return $user;
|
||||
}
|
||||
|
||||
/**
|
||||
* 사용자의 마지막 로그인 시간을 현재 시간으로 업데이트합니다.
|
||||
*
|
||||
@@ -552,7 +577,7 @@ class UserService
|
||||
$statusEnum = UserStatus::from($status);
|
||||
|
||||
// UUID → 정수 ID 변환 (내부 쿼리용)
|
||||
$userIds = User::whereIn('uuid', $uuids)->pluck('id')->toArray();
|
||||
$userIds = $this->userRepository->getIdsByUuids($uuids);
|
||||
|
||||
// DB 트랜잭션으로 일괄 업데이트
|
||||
$updatedCount = DB::transaction(function () use ($userIds, $statusEnum) {
|
||||
@@ -565,13 +590,11 @@ class UserService
|
||||
UserStatus::Inactive => $updateData,
|
||||
};
|
||||
|
||||
$count = User::whereIn('id', $userIds)->update($updateData);
|
||||
$count = $this->userRepository->updateManyByIds($userIds, $updateData);
|
||||
|
||||
// Active 외 상태로 변경 시 해당 사용자들의 토큰 전체 삭제
|
||||
if ($statusEnum !== UserStatus::Active) {
|
||||
PersonalAccessToken::where('tokenable_type', User::class)
|
||||
->whereIn('tokenable_id', $userIds)
|
||||
->delete();
|
||||
$this->userRepository->deleteTokensByUserIds($userIds);
|
||||
}
|
||||
|
||||
return $count;
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
<?php
|
||||
|
||||
namespace App\Support;
|
||||
|
||||
/**
|
||||
* 허용 확장자 목록 정규화 (#493 C2)
|
||||
*
|
||||
* 허용 확장자는 관리자 화면에서 콤마로 구분한 한 줄 텍스트로 들어오고, API 를 직접 쓰는
|
||||
* 경로에서는 배열로 들어온다. 저장 계층과 적용 계층이 각자 형태를 판단하면 한쪽이
|
||||
* 받아들이는 값을 다른 쪽이 조용히 버리게 되므로(관리자가 확장자를 바꿔도 업로드 제한은
|
||||
* 그대로), 형태 판정과 정규화를 이 한 곳에서만 수행한다.
|
||||
*/
|
||||
final class AllowedExtensions
|
||||
{
|
||||
/**
|
||||
* 문자열/배열 입력을 소문자 확장자 배열로 정규화합니다.
|
||||
*
|
||||
* @param mixed $value 콤마 구분 문자열 또는 배열
|
||||
* @return array<int, string> 정규화된 확장자 목록 (빈 배열 = 제한 없음)
|
||||
*/
|
||||
public static function normalize(mixed $value): array
|
||||
{
|
||||
if (is_string($value)) {
|
||||
$value = explode(',', $value);
|
||||
}
|
||||
|
||||
if (! is_array($value)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$normalized = [];
|
||||
|
||||
foreach ($value as $extension) {
|
||||
if (! is_string($extension) && ! is_numeric($extension)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$extension = strtolower(ltrim(trim((string) $extension), '.'));
|
||||
|
||||
if ($extension === '' || in_array($extension, $normalized, true)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$normalized[] = $extension;
|
||||
}
|
||||
|
||||
return $normalized;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user