v7.0.0 release
This commit is contained in:
1 parent
0e7fa04b03
commit
c4ea9a6cd1
3582 files changed
+626189
-160151
No files matched your search
+97
@@ -0,0 +1,97 @@
|
||||
<?php
|
||||
|
||||
namespace Plugins\Sirsoft\Gdpr\Http\Controllers\Admin;
|
||||
|
||||
use App\Helpers\ResponseHelper;
|
||||
use App\Http\Controllers\Api\Base\AdminBaseController;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Plugins\Sirsoft\Gdpr\Http\Resources\GdprConsentLogResource;
|
||||
use Plugins\Sirsoft\Gdpr\Services\GdprConsentLogService;
|
||||
|
||||
/**
|
||||
* GDPR 관리자 동의 로그 컨트롤러
|
||||
*
|
||||
* GET /api/plugins/sirsoft-gdpr/admin/consent-log
|
||||
*
|
||||
* 권한: consent-log.read (라우트 미들웨어에서 검증)
|
||||
*
|
||||
* `gdpr_user_consent_histories` 테이블의 페이지네이션·필터 조회를 제공합니다.
|
||||
* DPO 감사용 IP/User-Agent까지 노출됩니다.
|
||||
*/
|
||||
class GdprAdminConsentLogController extends AdminBaseController
|
||||
{
|
||||
/**
|
||||
* GdprAdminConsentLogController 생성자
|
||||
*
|
||||
* @param GdprConsentLogService $consentLogService 동의 로그 서비스
|
||||
*/
|
||||
public function __construct(
|
||||
private readonly GdprConsentLogService $consentLogService,
|
||||
) {
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
/**
|
||||
* 동의 로그 페이지네이션 응답을 반환합니다.
|
||||
*
|
||||
* 쿼리 파라미터:
|
||||
* - email: 회원 이메일 부분 일치
|
||||
* - session_id: 게스트 세션 ID 부분 일치 (DataGrid 가 앞 8자만 표시하므로 prefix/중간 모두 허용)
|
||||
* - consent_keys[]: 동의 항목 키 배열 (whereIn)
|
||||
* - actions[]: granted|revoked 배열
|
||||
* - sources[]: banner|preference_center|mypage 배열
|
||||
* - per_page: 페이지 크기 (1~100, 기본 20)
|
||||
*
|
||||
* @param Request $request HTTP 요청
|
||||
* @return JsonResponse
|
||||
*/
|
||||
public function index(Request $request): JsonResponse
|
||||
{
|
||||
$filters = [
|
||||
'email' => $request->query('email'),
|
||||
'session_id' => $request->query('session_id'),
|
||||
'consent_keys' => $this->normalizeArrayParam($request->query('consent_keys')),
|
||||
'actions' => $this->normalizeArrayParam($request->query('actions')),
|
||||
'sources' => $this->normalizeArrayParam($request->query('sources')),
|
||||
];
|
||||
|
||||
$perPage = max(1, min(100, (int) $request->query('per_page', 20)));
|
||||
|
||||
$paginator = $this->consentLogService->paginateForAdmin($filters, $perPage);
|
||||
|
||||
return ResponseHelper::success('messages.success', [
|
||||
'data' => GdprConsentLogResource::collection($paginator->items()),
|
||||
'pagination' => [
|
||||
'current_page' => $paginator->currentPage(),
|
||||
'last_page' => $paginator->lastPage(),
|
||||
'per_page' => $paginator->perPage(),
|
||||
'total' => $paginator->total(),
|
||||
'from' => $paginator->firstItem(),
|
||||
'to' => $paginator->lastItem(),
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 쿼리 파라미터 배열을 정규화합니다.
|
||||
*
|
||||
* `?consent_keys[]=a&consent_keys[]=b` → ['a', 'b']
|
||||
* `?consent_keys=a` → ['a'] (단일 값도 배열로 정규화)
|
||||
* `null` 또는 빈 값 → []
|
||||
*
|
||||
* @param mixed $value 쿼리 값
|
||||
* @return array<int, string>
|
||||
*/
|
||||
private function normalizeArrayParam(mixed $value): array
|
||||
{
|
||||
if ($value === null || $value === '') {
|
||||
return [];
|
||||
}
|
||||
if (is_array($value)) {
|
||||
return array_values(array_filter(array_map('strval', $value), fn ($v) => $v !== ''));
|
||||
}
|
||||
|
||||
return [(string) $value];
|
||||
}
|
||||
}
|
||||
+136
@@ -0,0 +1,136 @@
|
||||
<?php
|
||||
|
||||
namespace Plugins\Sirsoft\Gdpr\Http\Controllers\Admin;
|
||||
|
||||
use App\Helpers\ResponseHelper;
|
||||
use App\Http\Controllers\Api\Base\AdminBaseController;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Plugins\Sirsoft\Gdpr\Http\Requests\PublishPolicyVersionRequest;
|
||||
use Plugins\Sirsoft\Gdpr\Http\Resources\GdprPolicyVersionDetailResource;
|
||||
use Plugins\Sirsoft\Gdpr\Http\Resources\GdprPolicyVersionResource;
|
||||
use Plugins\Sirsoft\Gdpr\Services\GdprPolicyVersionService;
|
||||
use Plugins\Sirsoft\Gdpr\Services\GdprSettingsService;
|
||||
|
||||
/**
|
||||
* GDPR 관리자 정책 버전 컨트롤러
|
||||
*
|
||||
* - GET /api/plugins/sirsoft-gdpr/admin/policy-versions — 이력 페이지네이션
|
||||
* - GET /api/plugins/sirsoft-gdpr/admin/policy-versions/current — 현재 발행된 최신 버전
|
||||
* - POST /api/plugins/sirsoft-gdpr/admin/policy-versions — 운영자 수동 정책 버전 발행
|
||||
*
|
||||
* 권한: sirsoft-gdpr.privacy.view (조회) / sirsoft-gdpr.privacy.update (발행)
|
||||
*
|
||||
* GDPR Art.7(1) 동의 입증 책임 + Art.30 처리 기록 의무를 충족합니다.
|
||||
*/
|
||||
class GdprAdminPolicyVersionController extends AdminBaseController
|
||||
{
|
||||
/**
|
||||
* GdprAdminPolicyVersionController 생성자
|
||||
*
|
||||
* @param GdprPolicyVersionService $service 정책 버전 서비스
|
||||
* @param GdprSettingsService $settingsService 현재 settings snapshot 캡처용
|
||||
*/
|
||||
public function __construct(
|
||||
private readonly GdprPolicyVersionService $service,
|
||||
private readonly GdprSettingsService $settingsService,
|
||||
) {
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
/**
|
||||
* 정책 버전 이력을 페이지네이션 형태로 반환합니다 (version DESC).
|
||||
*
|
||||
* 쿼리 파라미터:
|
||||
* - per_page: 페이지 크기 (1~100, 기본 20)
|
||||
*
|
||||
* @param Request $request HTTP 요청
|
||||
* @return JsonResponse
|
||||
*/
|
||||
public function index(Request $request): JsonResponse
|
||||
{
|
||||
$perPage = max(1, min(100, (int) $request->query('per_page', 20)));
|
||||
|
||||
$paginator = $this->service->paginate($perPage);
|
||||
|
||||
return ResponseHelper::success('messages.success', [
|
||||
'data' => GdprPolicyVersionResource::collection($paginator->items()),
|
||||
'pagination' => [
|
||||
'current_page' => $paginator->currentPage(),
|
||||
'last_page' => $paginator->lastPage(),
|
||||
'per_page' => $paginator->perPage(),
|
||||
'total' => $paginator->total(),
|
||||
'from' => $paginator->firstItem(),
|
||||
'to' => $paginator->lastItem(),
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 운영자 수동 정책 버전 발행.
|
||||
*
|
||||
* 자동 감지 영역 (카테고리 key/description 변경, slug 변경) 밖의 변경 — 예:
|
||||
* - 정책 본문 페이지(sirsoft-page) 외부 수정
|
||||
* - 법인명 변경 후 의도적 재동의 트리거
|
||||
* - 운영 위탁자 변경 등 Art.13 정보 변경
|
||||
*
|
||||
* 호출 시 현재 settings snapshot 을 자동 캡처하여 새 정책 버전 발행
|
||||
* (settings 자체는 변경되지 않음 — 발행만 수행).
|
||||
*
|
||||
* @param PublishPolicyVersionRequest $request memo 필수 검증
|
||||
* @return JsonResponse
|
||||
*/
|
||||
public function store(PublishPolicyVersionRequest $request): JsonResponse
|
||||
{
|
||||
$memo = (string) $request->validated('memo');
|
||||
$snapshot = $this->settingsService->getCurrentSnapshot();
|
||||
|
||||
$version = $this->service->publishManually($snapshot, $memo, $request->user()?->id);
|
||||
|
||||
return ResponseHelper::success('sirsoft-gdpr::messages.settings.policy_version.publish_success', [
|
||||
'data' => new GdprPolicyVersionResource($version->load('createdBy')),
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 현재 발행된 최신 정책 버전을 반환합니다.
|
||||
*
|
||||
* 발행 row 가 없으면 data 가 null.
|
||||
*
|
||||
* @return JsonResponse
|
||||
*/
|
||||
public function current(): JsonResponse
|
||||
{
|
||||
$current = $this->service->getCurrent(loadCreatedBy: true);
|
||||
|
||||
return ResponseHelper::success('messages.success', [
|
||||
'data' => $current !== null ? new GdprPolicyVersionResource($current) : null,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 특정 정책 버전의 detail (snapshot 본문 포함) 을 반환합니다.
|
||||
*
|
||||
* admin 동의 이력 / 정책 버전 이력 화면에서 행 클릭 시 호출되어
|
||||
* 그 시점의 settings snapshot (cookie_categories / privacy_policy_slug / blocked_domains)
|
||||
* 을 모달로 표시. DPO 가 회원 분쟁 시 즉시 그 시점 정책 본문 확인 가능
|
||||
* (GDPR Art.7(1) 입증 책임 충족).
|
||||
*
|
||||
* 권한: sirsoft-gdpr.privacy.view (라우트 미들웨어에서 검증).
|
||||
*
|
||||
* @param int $version 조회할 정책 버전 정수 (URL path param)
|
||||
* @return JsonResponse 200 + detail / 404 (버전 부재)
|
||||
*/
|
||||
public function show(int $version): JsonResponse
|
||||
{
|
||||
$policyVersion = $this->service->getByVersion($version);
|
||||
|
||||
if ($policyVersion === null) {
|
||||
return ResponseHelper::error('sirsoft-gdpr::messages.settings.policy_version.not_found', 404);
|
||||
}
|
||||
|
||||
return ResponseHelper::success('messages.success', [
|
||||
'data' => new GdprPolicyVersionDetailResource($policyVersion),
|
||||
]);
|
||||
}
|
||||
}
|
||||
+109
@@ -0,0 +1,109 @@
|
||||
<?php
|
||||
|
||||
namespace Plugins\Sirsoft\Gdpr\Http\Controllers\Admin;
|
||||
|
||||
use App\Helpers\ResponseHelper;
|
||||
use App\Http\Controllers\Api\Base\AdminBaseController;
|
||||
use App\Services\PluginSettingsService;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Plugins\Sirsoft\Gdpr\Http\Requests\UpdateAdminSettingsRequest;
|
||||
use Plugins\Sirsoft\Gdpr\Services\GdprSettingsService;
|
||||
|
||||
/**
|
||||
* GDPR 관리자 설정 컨트롤러
|
||||
*
|
||||
* - GET /api/plugins/sirsoft-gdpr/admin/settings : 전체 설정 조회 (3탭)
|
||||
* - PUT /api/plugins/sirsoft-gdpr/admin/settings : 설정 저장 (정책 버전 발행 없음 — 수동 발행 전용)
|
||||
*
|
||||
* 권한: settings.manage (라우트 미들웨어에서 검증)
|
||||
*
|
||||
* 정책 버전 발행은 본 컨트롤러의 책임이 아닙니다. 운영자가 「+ 새 버전 발행」
|
||||
* (POST /admin/policy-versions) 으로 명시 트리거합니다 — GdprAdminPolicyVersionController.
|
||||
*/
|
||||
class GdprAdminSettingsController extends AdminBaseController
|
||||
{
|
||||
/**
|
||||
* 플러그인 식별자
|
||||
*/
|
||||
private const PLUGIN_ID = 'sirsoft-gdpr';
|
||||
|
||||
/**
|
||||
* GdprAdminSettingsController 생성자
|
||||
*
|
||||
* @param PluginSettingsService $pluginSettings 플러그인 설정 서비스 (코어 — 조회용)
|
||||
* @param GdprSettingsService $settingsService GDPR 설정 저장 서비스
|
||||
*/
|
||||
public function __construct(
|
||||
private readonly PluginSettingsService $pluginSettings,
|
||||
private readonly GdprSettingsService $settingsService,
|
||||
) {
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
/**
|
||||
* 현재 GDPR 플러그인 설정 전체를 반환합니다 (관리자 화면 폼 바인딩용).
|
||||
*
|
||||
* @return JsonResponse
|
||||
*/
|
||||
public function show(): JsonResponse
|
||||
{
|
||||
$settings = $this->pluginSettings->get(self::PLUGIN_ID);
|
||||
|
||||
$settings = $this->normalizeJsonFields(is_array($settings) ? $settings : []);
|
||||
|
||||
return ResponseHelper::success('messages.success', [
|
||||
'settings' => $settings,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* GDPR 플러그인 설정을 저장합니다.
|
||||
*
|
||||
* 정책 버전은 자동 발행되지 않습니다. 운영자가 별도로
|
||||
* 「+ 새 버전 발행」 을 클릭해야 발행됩니다.
|
||||
*
|
||||
* @param UpdateAdminSettingsRequest $request 검증된 요청
|
||||
* @return JsonResponse
|
||||
*/
|
||||
public function update(UpdateAdminSettingsRequest $request): JsonResponse
|
||||
{
|
||||
$validated = $request->validated();
|
||||
|
||||
// 동적 스키마 fallback (validation.md "동적 스키마 기반 FormRequest 패턴")
|
||||
if (empty($validated)) {
|
||||
$validated = $request->all();
|
||||
}
|
||||
|
||||
// 옛 자동 발행 흐름의 change_memo 필드는 더 이상 사용하지 않음 — 정책 버전 발행은 별도 엔드포인트로 일원화
|
||||
unset($validated['change_memo']);
|
||||
|
||||
$result = $this->settingsService->saveAdminSettings($validated);
|
||||
|
||||
return ResponseHelper::success('sirsoft-gdpr::messages.settings.saved', [
|
||||
'settings' => $this->normalizeJsonFields($result['settings']),
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 응답에서 JSON 필드는 디코드하여 객체/배열로 노출합니다.
|
||||
*
|
||||
* @param array<string, mixed> $settings 설정 배열
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function normalizeJsonFields(array $settings): array
|
||||
{
|
||||
foreach (['cookie_categories'] as $jsonKey) {
|
||||
if (! array_key_exists($jsonKey, $settings)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$value = $settings[$jsonKey];
|
||||
if (is_string($value)) {
|
||||
$decoded = json_decode($value, true);
|
||||
$settings[$jsonKey] = is_array($decoded) ? $decoded : [];
|
||||
}
|
||||
}
|
||||
|
||||
return $settings;
|
||||
}
|
||||
}
|
||||
+170
@@ -0,0 +1,170 @@
|
||||
<?php
|
||||
|
||||
namespace Plugins\Sirsoft\Gdpr\Http\Controllers\Public;
|
||||
|
||||
use App\Helpers\ResponseHelper;
|
||||
use App\Http\Controllers\Api\Base\PublicBaseController;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Plugins\Sirsoft\Gdpr\Http\Requests\StoreCookieConsentRequest;
|
||||
use Plugins\Sirsoft\Gdpr\Services\GdprConsentService;
|
||||
|
||||
/**
|
||||
* GDPR 공개 쿠키 동의 컨트롤러
|
||||
*
|
||||
* - POST /api/plugins/sirsoft-gdpr/consent/cookie : 게스트/회원 쿠키 동의 저장
|
||||
* - GET /api/plugins/sirsoft-gdpr/consent/cookie/status : 게스트/회원 쿠키 동의 현황 조회
|
||||
*
|
||||
* 인증 없이 접근 가능. 회원이 sanctum 토큰으로 호출하면 user_id 기반으로 저장.
|
||||
*/
|
||||
class GdprCookieConsentController extends PublicBaseController
|
||||
{
|
||||
/**
|
||||
* GdprCookieConsentController 생성자
|
||||
*
|
||||
* @param GdprConsentService $consentService GDPR 동의 서비스
|
||||
*/
|
||||
public function __construct(
|
||||
private readonly GdprConsentService $consentService,
|
||||
) {
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
/**
|
||||
* 게스트/회원 쿠키 동의를 저장합니다.
|
||||
*
|
||||
* 회원이면 user_id 기반 status upsert + history INSERT,
|
||||
* 게스트면 session_id 기반 history INSERT.
|
||||
*
|
||||
* @param StoreCookieConsentRequest $request 검증된 요청
|
||||
* @return JsonResponse
|
||||
*/
|
||||
public function store(StoreCookieConsentRequest $request): JsonResponse
|
||||
{
|
||||
$consents = (array) $request->validated('consents');
|
||||
$source = (string) $request->validated('source');
|
||||
|
||||
$userId = $request->user()?->id;
|
||||
$sessionId = null;
|
||||
$issuedSessionCookie = null;
|
||||
if ($userId === null) {
|
||||
$sessionId = $this->resolveGuestSessionId($request);
|
||||
if ($sessionId === null) {
|
||||
$sessionId = $this->issueGuestSessionId();
|
||||
$issuedSessionCookie = $sessionId;
|
||||
}
|
||||
}
|
||||
|
||||
$this->consentService->updateConsents($userId, $sessionId, $consents, $source);
|
||||
|
||||
$response = ResponseHelper::success('sirsoft-gdpr::messages.consent.granted', [
|
||||
'user_id' => $userId,
|
||||
'session_id' => $sessionId,
|
||||
'consents' => $consents,
|
||||
]);
|
||||
|
||||
if ($issuedSessionCookie !== null) {
|
||||
$this->attachGuestSessionCookie($response, $issuedSessionCookie);
|
||||
}
|
||||
|
||||
// Phase 2 단순화: 동의 철회 시 cookie 파기는 클라이언트 functionalCleaner 가 단독 담당.
|
||||
// 서버는 후속 응답에서 CookieConsentMiddleware 가 strictly necessary allowlist 외
|
||||
// 모든 Set-Cookie 를 제거 (EDPB §16) — 본 컨트롤러는 cookie 추가 발송 안 함.
|
||||
|
||||
return $response;
|
||||
}
|
||||
|
||||
/**
|
||||
* 현재 방문자(회원/게스트)의 쿠키 동의 상태를 반환합니다.
|
||||
*
|
||||
* 배너 표시 여부 결정용. has_consented = 현재 정책 버전으로 동의 완료 여부.
|
||||
* 회원이 sanctum 토큰으로 호출하면 user_id 기반, 미인증이면 session_id 기반.
|
||||
*
|
||||
* @param \Illuminate\Http\Request $request 요청
|
||||
* @return JsonResponse
|
||||
*/
|
||||
public function status(\Illuminate\Http\Request $request): JsonResponse
|
||||
{
|
||||
$userId = $request->user()?->id;
|
||||
$sessionId = $userId === null ? $this->resolveGuestSessionId($request) : null;
|
||||
|
||||
$hasConsented = $this->consentService->hasCurrentCookieConsent($userId, $sessionId);
|
||||
$consents = $this->consentService->getCurrentCookieConsents($userId, $sessionId);
|
||||
$currentPolicyVersion = $this->consentService->getCurrentPolicyVersion();
|
||||
|
||||
// needs_renewal: 옛 동의가 1건 이상 존재하는데 현재 정책 버전 미동의 (즉 옛 동의가 신정책에
|
||||
// 그대로 쓰이고 있는 상태). 신규 게스트 (동의 row 0건) 는 has_consented=false 지만
|
||||
// needs_renewal=false (재확인할 옛 동의 자체가 없음 — 일반 배너만 노출).
|
||||
// GDPR Art.6 보수적 차단 트리거 + A-6 배너 사유 안내 트리거 용도.
|
||||
$needsRenewal = ! $hasConsented
|
||||
&& $this->consentService->hasAnyConsentHistory($userId, $sessionId);
|
||||
|
||||
return ResponseHelper::success('messages.success', [
|
||||
'has_consented' => $hasConsented,
|
||||
'consents' => $consents,
|
||||
'needs_renewal' => $needsRenewal,
|
||||
'current_policy_version' => $currentPolicyVersion,
|
||||
// 회원/게스트 식별 SSoT — 배너 layout 이 회원 한정 keep_consent 버튼 분기에 사용.
|
||||
// optional.sanctum 미들웨어 통과 후 $request->user() 가 토큰 보유 회원이면 인스턴스 반환, 게스트면 null.
|
||||
'is_member' => $userId !== null,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 게스트 세션 ID를 결정합니다.
|
||||
*
|
||||
* 클라이언트가 쿠키 또는 헤더로 전달한 session_id가 있으면 사용,
|
||||
* 없으면 Laravel session ID를 fallback으로 사용합니다.
|
||||
*
|
||||
* @param \Illuminate\Http\Request $request 요청
|
||||
* @return string|null
|
||||
*/
|
||||
private function resolveGuestSessionId($request): ?string
|
||||
{
|
||||
$cookieValue = $request->cookie('gdpr_session');
|
||||
if (is_string($cookieValue) && $cookieValue !== '') {
|
||||
return substr($cookieValue, 0, 100);
|
||||
}
|
||||
|
||||
try {
|
||||
$sessionId = $request->hasSession() ? $request->session()->getId() : null;
|
||||
} catch (\Throwable) {
|
||||
$sessionId = null;
|
||||
}
|
||||
|
||||
return $sessionId !== null ? substr($sessionId, 0, 100) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 신규 게스트 세션 ID 를 발급합니다 (UUID v4 기반).
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
private function issueGuestSessionId(): string
|
||||
{
|
||||
return (string) \Illuminate\Support\Str::uuid();
|
||||
}
|
||||
|
||||
/**
|
||||
* 응답에 게스트 세션 쿠키 (gdpr_session) 를 첨부합니다.
|
||||
*
|
||||
* 1년 유효, path=/, SameSite=Lax. HTTPS 환경에서는 Secure 자동 적용.
|
||||
*
|
||||
* @param JsonResponse $response 응답
|
||||
* @param string $sessionId 발급된 세션 ID
|
||||
* @return void
|
||||
*/
|
||||
private function attachGuestSessionCookie(JsonResponse $response, string $sessionId): void
|
||||
{
|
||||
$response->cookie(
|
||||
'gdpr_session',
|
||||
$sessionId,
|
||||
60 * 24 * 365,
|
||||
'/',
|
||||
null,
|
||||
request()->isSecure(),
|
||||
true,
|
||||
false,
|
||||
'lax'
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
<?php
|
||||
|
||||
namespace Plugins\Sirsoft\Gdpr\Http\Controllers\Public;
|
||||
|
||||
use App\Helpers\ResponseHelper;
|
||||
use App\Http\Controllers\Api\Base\PublicBaseController;
|
||||
use App\Services\PluginSettingsService;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Plugins\Sirsoft\Gdpr\Plugin;
|
||||
use Plugins\Sirsoft\Gdpr\Services\CookieCategoryService;
|
||||
use Plugins\Sirsoft\Gdpr\Services\GdprPolicyVersionService;
|
||||
|
||||
/**
|
||||
* GDPR 공개 설정 컨트롤러
|
||||
*
|
||||
* 게스트도 접근 가능한 공개 설정을 반환합니다.
|
||||
* 배너·마이페이지 카드 렌더링에 필요한 expose 필드만 제공합니다.
|
||||
*
|
||||
* GET /api/plugins/sirsoft-gdpr/settings
|
||||
*/
|
||||
class GdprSettingsController extends PublicBaseController
|
||||
{
|
||||
/**
|
||||
* 플러그인 식별자
|
||||
*/
|
||||
private const PLUGIN_ID = 'sirsoft-gdpr';
|
||||
|
||||
/**
|
||||
* GdprSettingsController 생성자
|
||||
*
|
||||
* @param CookieCategoryService $categoryService 쿠키 카테고리 서비스
|
||||
* @param PluginSettingsService $pluginSettings 플러그인 설정 서비스
|
||||
* @param GdprPolicyVersionService $policyVersionService 정책 버전 서비스 (응답의 cookie_policy_version 출처)
|
||||
*/
|
||||
public function __construct(
|
||||
private readonly CookieCategoryService $categoryService,
|
||||
private readonly PluginSettingsService $pluginSettings,
|
||||
private readonly GdprPolicyVersionService $policyVersionService,
|
||||
) {
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
/**
|
||||
* 공개 설정 응답을 반환합니다.
|
||||
*
|
||||
* @return JsonResponse
|
||||
*/
|
||||
public function show(): JsonResponse
|
||||
{
|
||||
$privacySlug = (string) $this->pluginSettings->get(self::PLUGIN_ID, 'privacy_policy_slug', 'privacy');
|
||||
|
||||
$data = [
|
||||
// 정책 버전은 gdpr_policy_versions 테이블이 SSoT — 최신 row 의 version 정수를 string 으로 노출.
|
||||
// 회원/게스트 동의 시점 비교 (배너 재노출 판정) + 마이페이지의 자신의 동의 버전 vs 현재 비교에 사용.
|
||||
'cookie_policy_version' => (string) $this->policyVersionService->getCurrentVersion(),
|
||||
'privacy_policy_slug' => $privacySlug !== '' ? $privacySlug : null,
|
||||
'privacy_policy_available' => $privacySlug !== '',
|
||||
'legal_entity_name' => (string) $this->pluginSettings->get(self::PLUGIN_ID, 'legal_entity_name', ''),
|
||||
'data_storage_location' => (string) $this->pluginSettings->get(self::PLUGIN_ID, 'data_storage_location', ''),
|
||||
|
||||
// 쿠키 배너 + 자동 차단 (F-01 / F-02) — banner_enabled 단일 토글로 통합 제어.
|
||||
// 차단 엔진(클라이언트 blocker.ts) 의 활성 조건도 banner_enabled === true 단일.
|
||||
'banner_enabled' => (bool) $this->pluginSettings->get(self::PLUGIN_ID, 'banner_enabled', true),
|
||||
'banner_position' => (string) $this->pluginSettings->get(self::PLUGIN_ID, 'banner_position', 'bottom_bar'),
|
||||
'cookie_categories' => $this->categoryService->getCategories(),
|
||||
|
||||
// F-02 도메인 기반 차단 — 게스트도 차단 동작해야 하므로 공개 응답에 노출.
|
||||
// 본 컨트롤러가 응답 노출 SSoT (defaults.json 의 frontend_schema 는 보조).
|
||||
'blocked_domains' => $this->normalizeBlockedDomains(
|
||||
$this->pluginSettings->get(self::PLUGIN_ID, 'blocked_domains', Plugin::DEFAULT_BLOCKED_DOMAINS_CATALOG)
|
||||
),
|
||||
'default_blocked_domains_preview' => Plugin::DEFAULT_BLOCKED_DOMAINS_CATALOG,
|
||||
];
|
||||
|
||||
return ResponseHelper::success('messages.success', $data);
|
||||
}
|
||||
|
||||
/**
|
||||
* blocked_domains 응답 형식을 정규화합니다.
|
||||
*
|
||||
* 저장 형식이 native array 임을 가정하지만, JSON 문자열로 저장되어 있는 환경
|
||||
* (구버전 호환) 도 안전하게 처리합니다.
|
||||
*
|
||||
* @param mixed $value 설정 저장값
|
||||
* @return array<string, array<int, string>> 카테고리 → 도메인 패턴 배열
|
||||
*/
|
||||
private function normalizeBlockedDomains(mixed $value): array
|
||||
{
|
||||
if (is_string($value)) {
|
||||
$decoded = json_decode($value, true);
|
||||
$value = is_array($decoded) ? $decoded : [];
|
||||
}
|
||||
|
||||
if (! is_array($value)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$normalized = [];
|
||||
foreach ($value as $category => $domains) {
|
||||
if (! is_string($category)) {
|
||||
continue;
|
||||
}
|
||||
if (! is_array($domains)) {
|
||||
$normalized[$category] = [];
|
||||
|
||||
continue;
|
||||
}
|
||||
$normalized[$category] = array_values(array_filter(
|
||||
array_map(
|
||||
fn ($d) => is_string($d) ? trim($d) : '',
|
||||
$domains,
|
||||
),
|
||||
fn ($d) => $d !== '',
|
||||
));
|
||||
}
|
||||
|
||||
return $normalized;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
<?php
|
||||
|
||||
namespace Plugins\Sirsoft\Gdpr\Http\Controllers\User;
|
||||
|
||||
use App\Helpers\ResponseHelper;
|
||||
use App\Http\Controllers\Api\Base\AuthBaseController;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Plugins\Sirsoft\Gdpr\Http\Requests\GrantConsentRequest;
|
||||
use Plugins\Sirsoft\Gdpr\Http\Requests\RevokeConsentRequest;
|
||||
use Plugins\Sirsoft\Gdpr\Http\Resources\GdprUserConsentHistoryResource;
|
||||
use Plugins\Sirsoft\Gdpr\Http\Resources\GdprUserConsentResource;
|
||||
use Plugins\Sirsoft\Gdpr\Services\GdprConsentService;
|
||||
|
||||
/**
|
||||
* GDPR 회원 동의 컨트롤러
|
||||
*
|
||||
* - GET /api/plugins/sirsoft-gdpr/consent/me : 본인 활성 동의 동기화
|
||||
* - GET /api/plugins/sirsoft-gdpr/consent/history : 본인 동의 이력
|
||||
* - POST /api/plugins/sirsoft-gdpr/consent/revoke : 본인 동의 철회
|
||||
*/
|
||||
class GdprConsentController extends AuthBaseController
|
||||
{
|
||||
/**
|
||||
* GdprConsentController 생성자
|
||||
*
|
||||
* @param GdprConsentService $consentService GDPR 동의 서비스
|
||||
*/
|
||||
public function __construct(
|
||||
private readonly GdprConsentService $consentService,
|
||||
) {
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
/**
|
||||
* 본인 활성 동의 목록 (디바이스 간 동기화용).
|
||||
*
|
||||
* @return JsonResponse
|
||||
*/
|
||||
public function me(): JsonResponse
|
||||
{
|
||||
$user = $this->getCurrentUser();
|
||||
if ($user === null) {
|
||||
return $this->unauthorized();
|
||||
}
|
||||
|
||||
// 카탈로그의 모든 카테고리 ∪ 회원 status 매트릭스 (Art.7(3) 대칭성: 철회/재동의/신규 동의 한 화면 처리).
|
||||
// 마이페이지 「내 동의 현황」 표는 활성 동의만이 아니라 모든 카테고리를 노출하고
|
||||
// 상태별로 액션(철회/다시 동의/동의/필수 안내) 을 분기.
|
||||
$consents = $this->consentService->getMyConsentMatrix($user->id);
|
||||
|
||||
return ResponseHelper::success('messages.success', [
|
||||
'user_id' => $user->id,
|
||||
'needs_renewal' => $this->consentService->needsRenewal($user->id),
|
||||
'current_policy_version' => $this->consentService->getCurrentPolicyVersion(),
|
||||
'consents' => GdprUserConsentResource::collection($consents),
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 본인 동의 이력 (마이페이지 표시용).
|
||||
*
|
||||
* @return JsonResponse
|
||||
*/
|
||||
public function history(): JsonResponse
|
||||
{
|
||||
$user = $this->getCurrentUser();
|
||||
if ($user === null) {
|
||||
return $this->unauthorized();
|
||||
}
|
||||
|
||||
$histories = $this->consentService->getHistories($user->id);
|
||||
|
||||
return ResponseHelper::success('messages.success', [
|
||||
'histories' => GdprUserConsentHistoryResource::collection($histories),
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 본인 동의 철회.
|
||||
*
|
||||
* @param RevokeConsentRequest $request 검증된 요청
|
||||
* @return JsonResponse
|
||||
*/
|
||||
public function revoke(RevokeConsentRequest $request): JsonResponse
|
||||
{
|
||||
$user = $this->getCurrentUser();
|
||||
if ($user === null) {
|
||||
return $this->unauthorized();
|
||||
}
|
||||
|
||||
$consentKey = (string) $request->validated('consent_key');
|
||||
|
||||
$this->consentService->updateConsent(
|
||||
userId: $user->id,
|
||||
sessionId: null,
|
||||
consentKey: $consentKey,
|
||||
value: false,
|
||||
source: 'mypage',
|
||||
);
|
||||
|
||||
return ResponseHelper::success('sirsoft-gdpr::messages.consent.revoked', [
|
||||
'consent_key' => $consentKey,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 본인 동의 부여 (재동의 / 신규 동의).
|
||||
*
|
||||
* Art.7(3) 자유 변경권의 부여 방향 — 마이페이지 「내 동의 현황」 에서
|
||||
* 「다시 동의」 / 「동의」 버튼 클릭 시 호출. 화이트리스트 검사는 FormRequest 가 수행.
|
||||
*
|
||||
* @param GrantConsentRequest $request 검증된 요청
|
||||
* @return JsonResponse
|
||||
*/
|
||||
public function grant(GrantConsentRequest $request): JsonResponse
|
||||
{
|
||||
$user = $this->getCurrentUser();
|
||||
if ($user === null) {
|
||||
return $this->unauthorized();
|
||||
}
|
||||
|
||||
$consentKey = (string) $request->validated('consent_key');
|
||||
|
||||
$this->consentService->updateConsent(
|
||||
userId: $user->id,
|
||||
sessionId: null,
|
||||
consentKey: $consentKey,
|
||||
value: true,
|
||||
source: 'mypage',
|
||||
);
|
||||
|
||||
return ResponseHelper::success('sirsoft-gdpr::messages.consent.granted_again', [
|
||||
'consent_key' => $consentKey,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 정책 버전 bump 후 활성 선택형 동의를 일괄 새 버전으로 갱신합니다 (전체 항목 다시 동의 — #19).
|
||||
*
|
||||
* 필수 쿠키와 철회 상태는 대상 외. 의사 변경은 없으나 *재동의 의사 표명* 으로 처리되어
|
||||
* history 에 action=granted 행이 N개 누적됨 (각 갱신 항목당 1행, Art.7(1) 입증 트레일).
|
||||
*
|
||||
* @return JsonResponse
|
||||
*/
|
||||
public function renewAll(): JsonResponse
|
||||
{
|
||||
$user = $this->getCurrentUser();
|
||||
if ($user === null) {
|
||||
return $this->unauthorized();
|
||||
}
|
||||
|
||||
$renewed = $this->consentService->renewAllForCurrentPolicy($user->id);
|
||||
|
||||
// 시그니처: success($messageKey, $data, $statusCode, $messageParams, $domain).
|
||||
// renewed 카운트는 메시지 보간 (4번째 messageParams) 과 응답 페이로드 (2번째 data) 두 곳에
|
||||
// 모두 필요 — 프론트 toast 는 lang 의 {renewed} placeholder 를 토큰으로 직접 보간하지만,
|
||||
// 다른 클라이언트 (모바일/API 직접 호출) 가 응답 message 만 사용할 가능성 대비.
|
||||
return ResponseHelper::success(
|
||||
'sirsoft-gdpr::messages.consent.renew_all_success',
|
||||
['renewed' => $renewed],
|
||||
200,
|
||||
['renewed' => $renewed],
|
||||
);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
<?php
|
||||
|
||||
namespace Plugins\Sirsoft\Gdpr\Http\Middleware;
|
||||
|
||||
use Closure;
|
||||
use Illuminate\Contracts\Container\BindingResolutionException;
|
||||
use Illuminate\Http\Request;
|
||||
use Plugins\Sirsoft\Gdpr\Services\GdprConsentService;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
/**
|
||||
* Functional Cookie 동의 게이팅 미들웨어 (Phase 2 단순화 버전)
|
||||
*
|
||||
* EDPB Guidelines 2/2023 §16 (사전 차단) 충족:
|
||||
* - functional 미동의 시 응답 Set-Cookie 헤더에서 strictly necessary allowlist 외 모든 cookie 제거
|
||||
* - 운영자가 등록한 functional cookie 목록은 사용하지 않음 — GDPR 원칙은
|
||||
* "strictly necessary 외 비-필수는 동의 전 차단" 이므로 등록 표 불필요
|
||||
*
|
||||
* 파기 cookie (cleared) 는 항상 통과 — EDPB §117 (철회 즉시 파기) 와 본 §16 차단이 충돌하지 않도록.
|
||||
*
|
||||
* 등록 시점: `GdprServiceProvider::boot()` 에서 Laravel 11+ Kernel::prependMiddlewareToGroup('web'|'api') 호출.
|
||||
* Kernel.php:347 `array_search` 중복 방지로 매 요청 호출되어도 1회만 등록됨.
|
||||
*
|
||||
* @since 1.0.0-beta.1 (Phase 2)
|
||||
*/
|
||||
class CookieConsentMiddleware
|
||||
{
|
||||
/**
|
||||
* CookieConsentMiddleware 생성자
|
||||
*
|
||||
* @param GdprConsentService $consentService 동의 서비스 (현재 방문자 functional 동의 상태 조회)
|
||||
*/
|
||||
public function __construct(
|
||||
private readonly GdprConsentService $consentService,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* 요청 처리 — 응답 직전 functional cookie 게이팅.
|
||||
*
|
||||
* @param Request $request HTTP 요청
|
||||
* @param Closure $next 다음 미들웨어
|
||||
* @return Response HTTP 응답 (functional cookie 게이팅 적용)
|
||||
*/
|
||||
public function handle(Request $request, Closure $next): Response
|
||||
{
|
||||
/** @var Response $response */
|
||||
$response = $next($request);
|
||||
|
||||
// 1. functional 동의 여부 조회
|
||||
//
|
||||
// 자기 자신 (sirsoft-gdpr) 제거 응답 race condition 안전 통과:
|
||||
// 본 미들웨어는 라우트 진입 시점에 GdprServiceProvider::boot() 가 web/api 그룹에
|
||||
// prepend 한다. 운영자가 본 플러그인을 제거하는 요청이면 컨트롤러 단계에서 autoload
|
||||
// 갱신·활성 디렉토리 삭제가 발생하므로, 응답이 본 미들웨어로 돌아올 때 의존 클래스
|
||||
// (GdprPolicyVersionService 등) 로딩이 실패할 수 있다. 이 경우 cookie 게이팅을
|
||||
// 포기하고 응답을 그대로 통과시킨다 — 운영자의 "제거 성공" 흐름이 500 으로 깨지지
|
||||
// 않도록 한다. 그 외 일반 요청에서는 의존 클래스가 정상 로드되므로 동작 변경 없음.
|
||||
try {
|
||||
$hasConsent = $this->hasFunctionalConsent($request);
|
||||
} catch (BindingResolutionException) {
|
||||
return $response;
|
||||
}
|
||||
|
||||
if ($hasConsent) {
|
||||
return $response; // 동의 — 통과
|
||||
}
|
||||
|
||||
// 2. functional 미동의: 응답 Set-Cookie 중 strictly necessary allowlist 외 모두 제거
|
||||
foreach ($response->headers->getCookies() as $cookie) {
|
||||
$name = $cookie->getName();
|
||||
|
||||
// strictly necessary allowlist — 통과 (백엔드 cookie 4종)
|
||||
if ($this->isStrictlyNecessary($name)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// 파기 cookie (cleared) 는 통과 — §117 (철회 즉시 파기) 와 §16 (사전 차단) 충돌 회피.
|
||||
// GdprCookieConsentController 가 발송하는 Max-Age=0 cookie 도 본 분기로 통과 (현재는 미사용이나 안전 보장).
|
||||
if ($cookie->isCleared()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// 응답에서 Set-Cookie 제거 (EDPB §16 — 동의 전 신규 저장 금지)
|
||||
$response->headers->removeCookie($name, $cookie->getPath(), $cookie->getDomain());
|
||||
}
|
||||
|
||||
return $response;
|
||||
}
|
||||
|
||||
/**
|
||||
* 현재 방문자 (회원/게스트) 의 functional 동의 상태를 반환합니다.
|
||||
*
|
||||
* @param Request $request HTTP 요청
|
||||
* @return bool functional 동의 시 true
|
||||
*/
|
||||
private function hasFunctionalConsent(Request $request): bool
|
||||
{
|
||||
$userId = $request->user()?->id;
|
||||
$sessionId = $this->resolveGuestSessionId($request);
|
||||
|
||||
$consents = $this->consentService->getCurrentCookieConsents($userId, $sessionId);
|
||||
|
||||
return ($consents['functional'] ?? false) === true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 게스트 세션 식별자를 추출합니다 (gdpr_session cookie 또는 Laravel session ID).
|
||||
*
|
||||
* @param Request $request HTTP 요청
|
||||
* @return string|null 세션 식별자 (회원이거나 식별 불가 시 null)
|
||||
*/
|
||||
private function resolveGuestSessionId(Request $request): ?string
|
||||
{
|
||||
if ($request->user()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$cookieValue = $request->cookie('gdpr_session');
|
||||
if (is_string($cookieValue) && $cookieValue !== '') {
|
||||
return substr($cookieValue, 0, 100);
|
||||
}
|
||||
|
||||
try {
|
||||
return $request->hasSession() ? substr($request->session()->getId(), 0, 100) : null;
|
||||
} catch (\Throwable) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Strictly Necessary cookie 인지 판정합니다.
|
||||
*
|
||||
* ePrivacy Art.5(3) 면제 항목 — XSRF/세션/유지보수/GDPR 동의 관리 cookie 는 게이팅 대상 외.
|
||||
*
|
||||
* @param string $name cookie 이름
|
||||
* @return bool strictly necessary 시 true
|
||||
*/
|
||||
private function isStrictlyNecessary(string $name): bool
|
||||
{
|
||||
return in_array($name, [
|
||||
'XSRF-TOKEN',
|
||||
(string) config('session.cookie', 'laravel_session'),
|
||||
'laravel_maintenance',
|
||||
'gdpr_session',
|
||||
], true);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
<?php
|
||||
|
||||
namespace Plugins\Sirsoft\Gdpr\Http\Requests;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Plugins\Sirsoft\Gdpr\Services\CookieCategoryService;
|
||||
|
||||
/**
|
||||
* 회원 동의 부여(재동의/신규 동의) 요청 검증
|
||||
*
|
||||
* POST /api/plugins/sirsoft-gdpr/consent/grant
|
||||
*
|
||||
* 마이페이지 「내 동의 현황」 에서 「다시 동의」 / 「동의」 버튼 클릭 시 사용.
|
||||
* Art.7(3) 자유 변경권의 부여 방향 — 이미 철회한 항목을 다시 부여하거나, 카탈로그에 있지만
|
||||
* user_consents 에 row 없는 항목을 신규로 동의.
|
||||
*
|
||||
* 필수(strictly necessary) 카테고리는 부여 의미가 없지만(이미 항상 활성), 차단까지는 안 함 —
|
||||
* Art.7(3) 의 "자유 부여" 권리를 임의 차단하지 않기 위함. 결과적으로 noop 처리됨.
|
||||
*/
|
||||
class GrantConsentRequest extends FormRequest
|
||||
{
|
||||
/**
|
||||
* GrantConsentRequest 생성자
|
||||
*
|
||||
* @param CookieCategoryService $categoryService 쿠키 카테고리 설정 서비스
|
||||
*/
|
||||
public function __construct(private readonly CookieCategoryService $categoryService)
|
||||
{
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
/**
|
||||
* 권한 확인 (sanctum 인증은 미들웨어에서 처리)
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 검증 규칙 정의
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'consent_key' => ['required', 'string', 'max:50'],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 검증 메시지 정의
|
||||
*
|
||||
* @return array<string, string>
|
||||
*/
|
||||
public function messages(): array
|
||||
{
|
||||
return [
|
||||
'consent_key.required' => __('sirsoft-gdpr::messages.consent.invalid_key'),
|
||||
'consent_key.string' => __('sirsoft-gdpr::messages.consent.invalid_key'),
|
||||
'consent_key.max' => __('sirsoft-gdpr::messages.consent.invalid_key'),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 검증 후 동의 키 화이트리스트 검사.
|
||||
*
|
||||
* @param \Illuminate\Validation\Validator $validator
|
||||
* @return void
|
||||
*/
|
||||
public function withValidator(\Illuminate\Validation\Validator $validator): void
|
||||
{
|
||||
$validator->after(function (\Illuminate\Validation\Validator $validator) {
|
||||
$consentKey = (string) $this->input('consent_key', '');
|
||||
|
||||
if ($consentKey === '') {
|
||||
return;
|
||||
}
|
||||
|
||||
$allowedKeys = $this->categoryService->getAllConsentKeys();
|
||||
|
||||
if (! in_array($consentKey, $allowedKeys, true)) {
|
||||
$validator->errors()->add(
|
||||
'consent_key',
|
||||
__('sirsoft-gdpr::messages.consent.invalid_key')
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
<?php
|
||||
|
||||
namespace Plugins\Sirsoft\Gdpr\Http\Requests;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
|
||||
/**
|
||||
* 운영자 수동 정책 버전 발행 요청 검증
|
||||
*
|
||||
* POST /api/plugins/sirsoft-gdpr/admin/policy-versions
|
||||
*
|
||||
* 운영자가 정책 본문 외부 수정 등 *자동 감지 영역 밖* 의 변경을 인지하고
|
||||
* 명시적으로 새 정책 버전을 발행할 때 사용. memo 필수 (감사 추적).
|
||||
*/
|
||||
class PublishPolicyVersionRequest extends FormRequest
|
||||
{
|
||||
/**
|
||||
* 권한 확인 (permission 미들웨어에서 처리)
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 검증 규칙 정의
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'memo' => ['required', 'string', 'min:1', 'max:500'],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 검증 메시지의 :attribute placeholder 사용자 친화 라벨.
|
||||
*
|
||||
* @return array<string, string>
|
||||
*/
|
||||
public function attributes(): array
|
||||
{
|
||||
return [
|
||||
'memo' => __('sirsoft-gdpr::messages.settings.policy_version.material_modal.memo_label'),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
<?php
|
||||
|
||||
namespace Plugins\Sirsoft\Gdpr\Http\Requests;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Plugins\Sirsoft\Gdpr\Services\CookieCategoryService;
|
||||
|
||||
/**
|
||||
* 회원 동의 철회 요청 검증
|
||||
*
|
||||
* POST /api/plugins/sirsoft-gdpr/consent/revoke
|
||||
*
|
||||
* 마이페이지에서 본인 동의를 철회할 때 사용. 필수 카테고리는 422로 거부.
|
||||
*/
|
||||
class RevokeConsentRequest extends FormRequest
|
||||
{
|
||||
/**
|
||||
* RevokeConsentRequest 생성자
|
||||
*
|
||||
* @param CookieCategoryService $categoryService 쿠키 카테고리 설정 서비스
|
||||
*/
|
||||
public function __construct(private readonly CookieCategoryService $categoryService)
|
||||
{
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
/**
|
||||
* 권한 확인 (sanctum 인증은 미들웨어에서 처리)
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 검증 규칙 정의
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'consent_key' => ['required', 'string', 'max:50'],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 검증 메시지 정의
|
||||
*
|
||||
* @return array<string, string>
|
||||
*/
|
||||
public function messages(): array
|
||||
{
|
||||
return [
|
||||
'consent_key.required' => __('sirsoft-gdpr::messages.consent.invalid_key'),
|
||||
'consent_key.string' => __('sirsoft-gdpr::messages.consent.invalid_key'),
|
||||
'consent_key.max' => __('sirsoft-gdpr::messages.consent.invalid_key'),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 검증 후 동의 키 화이트리스트 + 필수 항목 차단.
|
||||
*
|
||||
* @param \Illuminate\Validation\Validator $validator
|
||||
* @return void
|
||||
*/
|
||||
public function withValidator(\Illuminate\Validation\Validator $validator): void
|
||||
{
|
||||
$validator->after(function (\Illuminate\Validation\Validator $validator) {
|
||||
$consentKey = (string) $this->input('consent_key', '');
|
||||
|
||||
if ($consentKey === '') {
|
||||
return;
|
||||
}
|
||||
|
||||
$allowedKeys = $this->categoryService->getAllConsentKeys();
|
||||
|
||||
if (! in_array($consentKey, $allowedKeys, true)) {
|
||||
$validator->errors()->add(
|
||||
'consent_key',
|
||||
__('sirsoft-gdpr::messages.consent.invalid_key')
|
||||
);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if ($this->categoryService->isRequired($consentKey)) {
|
||||
$validator->errors()->add(
|
||||
'consent_key',
|
||||
__('sirsoft-gdpr::messages.consent.required_cannot_revoke')
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
<?php
|
||||
|
||||
namespace Plugins\Sirsoft\Gdpr\Http\Requests;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Plugins\Sirsoft\Gdpr\Services\CookieCategoryService;
|
||||
|
||||
/**
|
||||
* 쿠키 동의 저장 요청 검증
|
||||
*
|
||||
* POST /api/plugins/sirsoft-gdpr/consent/cookie
|
||||
*
|
||||
* 게스트(미인증) / 회원(sanctum) 모두 호출 가능한 공개 엔드포인트.
|
||||
* 게스트는 session_id 기반 history INSERT, 회원은 status upsert + history INSERT.
|
||||
*/
|
||||
class StoreCookieConsentRequest extends FormRequest
|
||||
{
|
||||
/**
|
||||
* StoreCookieConsentRequest 생성자
|
||||
*
|
||||
* @param CookieCategoryService $categoryService 쿠키 카테고리 설정 서비스
|
||||
*/
|
||||
public function __construct(private readonly CookieCategoryService $categoryService)
|
||||
{
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
/**
|
||||
* 권한 확인 (공개 엔드포인트 — 인증 불필요)
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 검증 규칙 정의
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'consents' => ['required', 'array', 'min:1'],
|
||||
'consents.*' => ['required', 'boolean'],
|
||||
'source' => ['required', 'string', 'in:banner,preference_center,register,mypage'],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 검증 메시지 정의
|
||||
*
|
||||
* @return array<string, string>
|
||||
*/
|
||||
public function messages(): array
|
||||
{
|
||||
return [
|
||||
'consents.required' => __('sirsoft-gdpr::messages.consent.invalid_key'),
|
||||
'consents.array' => __('sirsoft-gdpr::messages.consent.invalid_key'),
|
||||
'consents.*.boolean' => __('sirsoft-gdpr::messages.consent.invalid_key'),
|
||||
'source.required' => __('sirsoft-gdpr::messages.consent.invalid_key'),
|
||||
'source.in' => __('sirsoft-gdpr::messages.consent.invalid_key'),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 검증 후 동의 키 화이트리스트 + 필수 항목 false 차단.
|
||||
*
|
||||
* @param \Illuminate\Validation\Validator $validator
|
||||
* @return void
|
||||
*/
|
||||
public function withValidator(\Illuminate\Validation\Validator $validator): void
|
||||
{
|
||||
$validator->after(function (\Illuminate\Validation\Validator $validator) {
|
||||
$consents = (array) $this->input('consents', []);
|
||||
$allowedKeys = $this->categoryService->getAllConsentKeys();
|
||||
|
||||
foreach ($consents as $key => $value) {
|
||||
if (! in_array($key, $allowedKeys, true)) {
|
||||
$validator->errors()->add(
|
||||
"consents.{$key}",
|
||||
__('sirsoft-gdpr::messages.consent.invalid_key')
|
||||
);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($value === false && $this->categoryService->isRequired($key)) {
|
||||
$validator->errors()->add(
|
||||
"consents.{$key}",
|
||||
__('sirsoft-gdpr::messages.consent.required_cannot_revoke')
|
||||
);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,265 @@
|
||||
<?php
|
||||
|
||||
namespace Plugins\Sirsoft\Gdpr\Http\Requests;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
|
||||
/**
|
||||
* 관리자 GDPR 설정 저장 요청 검증
|
||||
*
|
||||
* PUT /api/plugins/sirsoft-gdpr/admin/settings
|
||||
*
|
||||
* 운영자가 설정 화면에서 정책 메타데이터·쿠키 배너·마이페이지 카드 토글을
|
||||
* 저장할 때 사용. plugin.php::getSettingsSchema() 와 키 일치를 보장합니다.
|
||||
*/
|
||||
class UpdateAdminSettingsRequest extends FormRequest
|
||||
{
|
||||
/**
|
||||
* 배너 위치 허용 값
|
||||
*/
|
||||
private const BANNER_POSITIONS = [
|
||||
'bottom_bar',
|
||||
'bottom_left_popup',
|
||||
'bottom_right_popup',
|
||||
'centered_modal',
|
||||
];
|
||||
|
||||
/**
|
||||
* 차단 도메인 정규식
|
||||
*
|
||||
* - FQDN 만 허용 (점 1개 이상 — RFC 1035 기반)
|
||||
* - 와일드카드 prefix `*.` 허용 (예: *.hotjar.com)
|
||||
* - 하이픈은 라벨 시작/끝 금지 (RFC 1035)
|
||||
* - 대소문자 무관
|
||||
* - 숫자만으로 구성된 라벨 허용 (예: 1.2.3.4 는 IPv4 처럼 보이지만 정규식상 통과 — 실제 DNS 동작은 CDN/PaaS 에 의존)
|
||||
* - punycode·localhost·단일 라벨 도메인 미지원 (운영자 안내 박스 hint 명시)
|
||||
*/
|
||||
private const DOMAIN_REGEX = '/^(\*\.)?[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)+$/i';
|
||||
|
||||
/**
|
||||
* 권한 확인 (permission 미들웨어에서 처리)
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 검증 규칙 정의
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
// 정책 메타데이터 — cookie_policy_version 은 gdpr_policy_versions 테이블이 SSoT.
|
||||
// 운영자가 직접 입력하지 않으므로 본 FormRequest 에서 검증하지 않음 (전달되어도 stripped).
|
||||
'privacy_policy_slug' => ['nullable', 'string', 'max:100', 'regex:/^[a-z0-9\-]*$/'],
|
||||
'legal_entity_name' => ['nullable', 'string', 'max:200'],
|
||||
// 데이터 저장 위치 — GDPR Art.13(1)(f) / PIPA 28조의8 은 "국가 단위" 표기를 요구.
|
||||
// 운영자가 실수로 보안 민감 식별자 (IP / CIDR / AWS 리전 코드) 를 입력하지 않도록
|
||||
// not_regex 3종으로 차단. 통과한 일반 텍스트는 운영자 자유 입력 허용.
|
||||
'data_storage_location' => [
|
||||
'nullable',
|
||||
'string',
|
||||
'max:200',
|
||||
'not_regex:/\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}(\/\d{1,2})?\b/', // IPv4 / CIDR
|
||||
'not_regex:/\b[a-z]{2,}-[a-z]+(-\d+[a-z]?|\d+)\b/i', // 리전 코드: AWS ap-northeast-2, GCP asia-northeast3, Azure eastus2 패턴
|
||||
'not_regex:/\b(us|eu|ap|me|af|sa|ca)-(east|west|north|south|central|northeast|southeast|northwest|southwest)\b/i', // 리전 prefix 만 입력해도 차단 (예: us-east, ap-northeast)
|
||||
],
|
||||
|
||||
// 쿠키 배너 + 자동 차단 (F-01 / F-02) — banner_enabled 단일 토글로 통합 제어.
|
||||
// auto_blocking_enabled 별도 검증 규칙 없음: 운영자가 PUT 으로 키를 보내도 stripped.
|
||||
'banner_enabled' => ['nullable', 'boolean'],
|
||||
'banner_position' => ['nullable', 'string', 'in:'.implode(',', self::BANNER_POSITIONS)],
|
||||
// cookie_categories.*.required 는 운영자 입력 경로가 없으므로 검증하지 않음 (CookieCategory enum 이 SSoT).
|
||||
'cookie_categories' => ['nullable'],
|
||||
'cookie_categories.*.key' => ['required_with:cookie_categories', 'string', 'in:necessary,functional,analytics,marketing'],
|
||||
'cookie_categories.*.label' => ['required_with:cookie_categories', 'array'],
|
||||
'cookie_categories.*.label.ko' => ['required_with:cookie_categories', 'string', 'max:50'],
|
||||
'cookie_categories.*.label.en' => ['required_with:cookie_categories', 'string', 'max:50'],
|
||||
'cookie_categories.*.description' => ['nullable', 'array'],
|
||||
|
||||
// F-02 도메인 기반 차단
|
||||
'blocked_domains' => ['nullable', 'array'],
|
||||
'blocked_domains.*' => ['array'],
|
||||
'blocked_domains.*.*' => ['string', 'max:253', 'regex:'.self::DOMAIN_REGEX],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 검증 메시지 정의
|
||||
*
|
||||
* @return array<string, string>
|
||||
*/
|
||||
public function messages(): array
|
||||
{
|
||||
return [
|
||||
'data_storage_location.not_regex' => __('sirsoft-gdpr::messages.settings.fields.data_storage_location.sensitive_format'),
|
||||
'cookie_categories.*.key.in' => __('sirsoft-gdpr::messages.consent.invalid_key'),
|
||||
// 카테고리별 메시지 — 운영자가 어떤 카테고리의 어느 도메인이 잘못됐는지 즉시 식별 가능.
|
||||
// GDPR 4카테고리 중 necessary 는 차단 대상 아님 → functional / analytics / marketing 만 정의.
|
||||
'blocked_domains.functional.*.regex' => __('sirsoft-gdpr::messages.blocked_domains.invalid_format_functional'),
|
||||
'blocked_domains.functional.*.max' => __('sirsoft-gdpr::messages.blocked_domains.too_long_functional'),
|
||||
'blocked_domains.analytics.*.regex' => __('sirsoft-gdpr::messages.blocked_domains.invalid_format_analytics'),
|
||||
'blocked_domains.analytics.*.max' => __('sirsoft-gdpr::messages.blocked_domains.too_long_analytics'),
|
||||
'blocked_domains.marketing.*.regex' => __('sirsoft-gdpr::messages.blocked_domains.invalid_format_marketing'),
|
||||
'blocked_domains.marketing.*.max' => __('sirsoft-gdpr::messages.blocked_domains.too_long_marketing'),
|
||||
'blocked_domains.*.array' => __('sirsoft-gdpr::messages.blocked_domains.must_be_array'),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 검증 메시지의 :attribute placeholder 를 사용자 친화 한국어/영어 라벨로 치환.
|
||||
*
|
||||
* Laravel 기본 :attribute 는 underscore 만 공백으로 치환한 영문 표현 (예: "privacy policy slug")
|
||||
* 노출 → 사용자 친화도 낮음. 본 메서드로 각 필드에 한국어/영어 라벨 매핑.
|
||||
*
|
||||
* 라벨 출처는 lang/{locale}/messages.php 의 settings.fields.{field}.label 키.
|
||||
*
|
||||
* @return array<string, string>
|
||||
*/
|
||||
public function attributes(): array
|
||||
{
|
||||
return [
|
||||
// cookie_policy_version 은 자동 발행이므로 FormRequest 가 검증하지 않음 (attributes 도 불필요).
|
||||
'privacy_policy_slug' => __('sirsoft-gdpr::messages.settings.fields.privacy_policy_slug.label'),
|
||||
'legal_entity_name' => __('sirsoft-gdpr::messages.settings.fields.legal_entity_name.label'),
|
||||
'data_storage_location' => __('sirsoft-gdpr::messages.settings.fields.data_storage_location.label'),
|
||||
'banner_enabled' => __('sirsoft-gdpr::messages.settings.fields.banner_enabled.label'),
|
||||
'banner_position' => __('sirsoft-gdpr::messages.settings.fields.banner_position.label'),
|
||||
'cookie_categories' => __('sirsoft-gdpr::messages.settings.section.cookie_categories'),
|
||||
'blocked_domains' => __('sirsoft-gdpr::messages.settings.section.auto_blocking'),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 사전 정규화:
|
||||
* 1. cookie_categories 가 JSON 문자열로 들어와도 array 로 변환
|
||||
* 2. blocked_domains 의 카테고리별 값이 textarea 줄바꿈 문자열이면 배열로 변환
|
||||
* (한 줄당 도메인 하나, 빈 줄 제거, trim)
|
||||
* 3. cookie_categories 의 키 중 necessary 제외한 모든 키가 blocked_domains 에
|
||||
* 존재하도록 빈 배열로 자동 보충 (운영자가 새 카테고리 추가 시 UI iteration
|
||||
* 미렌더·검증 실패 방지)
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected function prepareForValidation(): void
|
||||
{
|
||||
$cookieCategories = $this->normalizeJsonArray($this->input('cookie_categories'));
|
||||
|
||||
$blockedDomains = $this->normalizeBlockedDomains(
|
||||
$this->input('blocked_domains'),
|
||||
is_array($cookieCategories) ? $cookieCategories : [],
|
||||
);
|
||||
|
||||
$merge = ['cookie_categories' => $cookieCategories];
|
||||
if ($blockedDomains !== null) {
|
||||
$merge['blocked_domains'] = $blockedDomains;
|
||||
}
|
||||
|
||||
$this->merge($merge);
|
||||
}
|
||||
|
||||
/**
|
||||
* blocked_domains 입력을 정규화합니다.
|
||||
*
|
||||
* 카테고리별 값이 string 이면 줄바꿈으로 split → trim → 빈 항목 제거.
|
||||
* 이미 array 면 그대로 보존. cookie_categories 의 키 (necessary 제외) 가
|
||||
* blocked_domains 에 없으면 빈 배열로 보충하여 UI iteration·검증 실패를 방지합니다.
|
||||
*
|
||||
* @param mixed $input blocked_domains 입력값
|
||||
* @param array $cookieCategories cookie_categories 정규화된 배열
|
||||
* @return array<string, array<int, string>>|null
|
||||
*/
|
||||
private function normalizeBlockedDomains(mixed $input, array $cookieCategories): ?array
|
||||
{
|
||||
if ($input === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (! is_array($input)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$normalized = [];
|
||||
foreach ($input as $category => $value) {
|
||||
if (is_string($value)) {
|
||||
$normalized[$category] = collect(preg_split('/\R/', $value))
|
||||
->map(fn ($line) => is_string($line) ? trim($line) : '')
|
||||
->filter(fn ($line) => $line !== '')
|
||||
->values()
|
||||
->all();
|
||||
} elseif (is_array($value)) {
|
||||
$normalized[$category] = array_values(array_filter(
|
||||
array_map(fn ($line) => is_string($line) ? trim($line) : '', $value),
|
||||
fn ($line) => $line !== '',
|
||||
));
|
||||
} else {
|
||||
$normalized[$category] = [];
|
||||
}
|
||||
}
|
||||
|
||||
// cookie_categories 의 키 (necessary 제외) 가 blocked_domains 에 없으면 빈 배열로 보충
|
||||
foreach ($cookieCategories as $category) {
|
||||
$key = is_array($category) ? ($category['key'] ?? null) : null;
|
||||
if (! is_string($key) || $key === '' || $key === 'necessary') {
|
||||
continue;
|
||||
}
|
||||
if (! array_key_exists($key, $normalized)) {
|
||||
$normalized[$key] = [];
|
||||
}
|
||||
}
|
||||
|
||||
return $normalized;
|
||||
}
|
||||
|
||||
/**
|
||||
* 검증 후 cookie_categories 내 key 중복 차단.
|
||||
*
|
||||
* @param \Illuminate\Validation\Validator $validator
|
||||
* @return void
|
||||
*/
|
||||
public function withValidator(\Illuminate\Validation\Validator $validator): void
|
||||
{
|
||||
$validator->after(function (\Illuminate\Validation\Validator $validator) {
|
||||
$categories = (array) $this->input('cookie_categories', []);
|
||||
$keys = array_column($categories, 'key');
|
||||
if (count($keys) !== count(array_unique($keys))) {
|
||||
$validator->errors()->add(
|
||||
'cookie_categories',
|
||||
__('sirsoft-gdpr::messages.consent.invalid_key')
|
||||
);
|
||||
}
|
||||
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* JSON 문자열 또는 배열을 array 로 정규화합니다.
|
||||
*
|
||||
* @param mixed $value 입력 값
|
||||
* @return array|null
|
||||
*/
|
||||
private function normalizeJsonArray(mixed $value): ?array
|
||||
{
|
||||
if ($value === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (is_array($value)) {
|
||||
return $value;
|
||||
}
|
||||
|
||||
if (is_string($value)) {
|
||||
$decoded = json_decode($value, true);
|
||||
if (is_array($decoded)) {
|
||||
return $decoded;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
<?php
|
||||
|
||||
namespace Plugins\Sirsoft\Gdpr\Http\Resources;
|
||||
|
||||
use App\Http\Resources\BaseApiResource;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
/**
|
||||
* GDPR 관리자 동의 로그 API 리소스
|
||||
*
|
||||
* `gdpr_user_consent_histories` 행을 관리자 화면용으로 변환합니다.
|
||||
* IP/User-Agent까지 노출하여 DPO 감사 조회를 지원하며,
|
||||
* 사용자 정보는 whenLoaded()로 관계 로딩 시에만 포함됩니다.
|
||||
*/
|
||||
class GdprConsentLogResource extends BaseApiResource
|
||||
{
|
||||
/**
|
||||
* 리소스를 배열로 변환합니다.
|
||||
*
|
||||
* @param Request $request HTTP 요청
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'user_id' => $this->user_id,
|
||||
'session_id' => $this->session_id,
|
||||
'consent_key' => $this->consent_key,
|
||||
'action' => $this->action,
|
||||
'source' => $this->source,
|
||||
'policy_version' => $this->policy_version,
|
||||
'categories' => $this->categories,
|
||||
'categories_snapshot' => $this->buildCategoriesSnapshot(),
|
||||
'ip_address' => $this->ip_address,
|
||||
'user_agent' => $this->user_agent,
|
||||
'created_at' => $this->formatDateTimeStringForUser($this->created_at),
|
||||
'user' => $this->whenLoaded('user', fn () => $this->user !== null ? [
|
||||
'id' => $this->user->id,
|
||||
'uuid' => $this->user->uuid,
|
||||
'name' => $this->user->name,
|
||||
'email' => $this->user->email,
|
||||
] : null),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 카테고리 스냅샷 표시 순서 — 필수 → 분석 → 마케팅 (위계: 거부 불가 → 선택 항목).
|
||||
*
|
||||
* MySQL JSON 컬럼이 키를 알파벳 순으로 정규화 저장하므로 (analytics → marketing → necessary)
|
||||
* Resource 단계에서 UX 위계 순서로 재정렬한다. 카탈로그 외 키는 본 배열의 마지막에 원래 순서로 노출.
|
||||
*/
|
||||
private const SNAPSHOT_PRIORITY = [
|
||||
'cookie_necessary',
|
||||
'cookie_analytics',
|
||||
'cookie_marketing',
|
||||
];
|
||||
|
||||
/**
|
||||
* 카테고리 스냅샷을 iteration 친화 배열로 변환합니다.
|
||||
*
|
||||
* 저장 형식 {"cookie_necessary": true, "cookie_analytics": false} 는
|
||||
* G7 layout iteration 이 객체 순회를 지원하지 않으므로 admin 화면 표시용 배열로 변환합니다.
|
||||
* 라벨은 프론트가 `consent.category_{key}` 다국어 키로 해석합니다 (이미 정의된 키 재사용).
|
||||
*
|
||||
* @return array<int, array{key: string, label_key: string, granted: bool}>|null
|
||||
*/
|
||||
protected function buildCategoriesSnapshot(): ?array
|
||||
{
|
||||
$categories = $this->categories;
|
||||
|
||||
if (! is_array($categories) || $categories === []) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$ordered = [];
|
||||
foreach (self::SNAPSHOT_PRIORITY as $priorityKey) {
|
||||
if (array_key_exists($priorityKey, $categories)) {
|
||||
$ordered[$priorityKey] = $categories[$priorityKey];
|
||||
}
|
||||
}
|
||||
foreach ($categories as $key => $granted) {
|
||||
if (! array_key_exists($key, $ordered)) {
|
||||
$ordered[$key] = $granted;
|
||||
}
|
||||
}
|
||||
|
||||
$snapshot = [];
|
||||
foreach ($ordered as $key => $granted) {
|
||||
$snapshot[] = [
|
||||
'key' => (string) $key,
|
||||
'label_key' => 'sirsoft-gdpr.consent.category_'.$key,
|
||||
'granted' => (bool) $granted,
|
||||
];
|
||||
}
|
||||
|
||||
return $snapshot;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
<?php
|
||||
|
||||
namespace Plugins\Sirsoft\Gdpr\Http\Resources;
|
||||
|
||||
use App\Http\Resources\BaseApiResource;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
/**
|
||||
* GDPR 정책 버전 detail API 리소스 (admin snapshot 모달용)
|
||||
*
|
||||
* `gdpr_policy_versions` 단일 행을 admin 동의 이력 / 정책 버전 이력 화면의
|
||||
* snapshot 모달용으로 변환합니다. 목록용 `GdprPolicyVersionResource` 와 달리
|
||||
* `snapshot` 본문 (cookie_categories / privacy_policy_slug / blocked_domains)
|
||||
* 을 포함하여 DPO 가 그 시점 정책 본문을 즉시 확인 가능 (Art.7(1) 입증 책임).
|
||||
*
|
||||
* 발행 운영자 정보 (id/uuid/name/email) 는 createdBy 관계가 로드된 경우만 포함됩니다.
|
||||
*/
|
||||
class GdprPolicyVersionDetailResource extends BaseApiResource
|
||||
{
|
||||
/**
|
||||
* 리소스를 배열로 변환합니다.
|
||||
*
|
||||
* @param Request $request HTTP 요청
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'version' => $this->version,
|
||||
'change_type' => $this->change_type->value,
|
||||
'memo' => $this->memo,
|
||||
'created_at' => $this->formatDateTimeStringForUser($this->created_at),
|
||||
// 발행 시점 settings snapshot 전체 (immutable). admin 권한 가드를 통과한 호출자만 접근.
|
||||
'snapshot' => $this->snapshot,
|
||||
// 차단 도메인 카탈로그를 프론트 iteration 친화 배열로 변환:
|
||||
// { analytics: [...], marketing: [...] } → [{ category, domains }, ...]
|
||||
// G7 표현식 엔진이 Object.entries 미지원이라 객체 직접 iteration 불가 → 백엔드에서 변환.
|
||||
'blocked_domains_list' => $this->mapBlockedDomainsToArray(),
|
||||
// 발행 운영자 정보 (관계 로드 시에만). raw FK (created_by) 는 노출하지 않고
|
||||
// 관계 데이터 (uuid/name/email) 만 노출.
|
||||
'publisher' => $this->whenLoaded('createdBy', fn () => $this->createdBy !== null ? [
|
||||
'uuid' => $this->createdBy->uuid,
|
||||
'name' => $this->createdBy->name,
|
||||
'email' => $this->createdBy->email,
|
||||
] : null),
|
||||
...$this->resourceMeta($request),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* snapshot.blocked_domains 의 카테고리→도메인 객체를 프론트 iteration 친화 배열로 변환.
|
||||
*
|
||||
* 입력: ['analytics' => ['google-analytics.com', ...], 'marketing' => [...]]
|
||||
* 출력: [['category' => 'analytics', 'domains' => [...]], ['category' => 'marketing', 'domains' => [...]]]
|
||||
*
|
||||
* 카테고리 순서는 입력 키 순서를 보존 (PHP 연관 배열 특성).
|
||||
* snapshot.blocked_domains 가 없거나 객체가 아니면 빈 배열 반환.
|
||||
*
|
||||
* @return array<int, array{category: string, domains: array<int, string>}>
|
||||
*/
|
||||
private function mapBlockedDomainsToArray(): array
|
||||
{
|
||||
$blockedDomains = $this->snapshot['blocked_domains'] ?? null;
|
||||
|
||||
if (! is_array($blockedDomains)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$result = [];
|
||||
foreach ($blockedDomains as $category => $domains) {
|
||||
if (! is_array($domains)) {
|
||||
continue;
|
||||
}
|
||||
$result[] = [
|
||||
'category' => (string) $category,
|
||||
'domains' => array_values(array_map('strval', $domains)),
|
||||
];
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
<?php
|
||||
|
||||
namespace Plugins\Sirsoft\Gdpr\Http\Resources;
|
||||
|
||||
use App\Http\Resources\BaseApiResource;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
/**
|
||||
* GDPR 정책 버전 API 리소스
|
||||
*
|
||||
* `gdpr_policy_versions` 단일 행을 관리자 이력 모달용으로 변환합니다.
|
||||
* 발행 운영자 정보 (id/uuid/name/email) 는 createdBy 관계가 로드된 경우만 포함됩니다.
|
||||
*/
|
||||
class GdprPolicyVersionResource extends BaseApiResource
|
||||
{
|
||||
/**
|
||||
* 리소스를 배열로 변환합니다.
|
||||
*
|
||||
* @param Request $request HTTP 요청
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'version' => $this->version,
|
||||
'change_type' => $this->change_type->value,
|
||||
'memo' => $this->memo,
|
||||
'created_at' => $this->formatDateTimeStringForUser($this->created_at),
|
||||
// 발행 운영자 정보 (관계 로드 시에만). raw FK (created_by) 는 노출하지 않고
|
||||
// 관계 데이터 (uuid/name/email) 만 노출 — 민감 정보 노출 최소화.
|
||||
'publisher' => $this->whenLoaded('createdBy', fn () => $this->createdBy !== null ? [
|
||||
'uuid' => $this->createdBy->uuid,
|
||||
'name' => $this->createdBy->name,
|
||||
'email' => $this->createdBy->email,
|
||||
] : null),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
<?php
|
||||
|
||||
namespace Plugins\Sirsoft\Gdpr\Http\Resources;
|
||||
|
||||
use App\Http\Resources\BaseApiResource;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
/**
|
||||
* GDPR 동의 변경 이력 API 리소스
|
||||
*
|
||||
* `gdpr_user_consent_histories` (immutable append-only) 단일 행을 응답으로 변환.
|
||||
* 마이페이지의 동의 이력 표시 + DPO 감사 조회용.
|
||||
*
|
||||
* 민감 정보 처리:
|
||||
* - 사용자(마이페이지) 컨텍스트는 자기 IP/UA를 그대로 보여줘도 무방
|
||||
* - 관리자(consent log) 컨텍스트는 GdprConsentLogResource 별도 사용
|
||||
*/
|
||||
class GdprUserConsentHistoryResource extends BaseApiResource
|
||||
{
|
||||
/**
|
||||
* 리소스를 배열로 변환합니다.
|
||||
*
|
||||
* @param Request $request HTTP 요청
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'consent_key' => $this->consent_key,
|
||||
'action' => $this->action,
|
||||
'source' => $this->source,
|
||||
'policy_version' => $this->policy_version,
|
||||
'categories' => $this->categories,
|
||||
'created_at' => $this->formatDateTimeStringForUser($this->created_at),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
<?php
|
||||
|
||||
namespace Plugins\Sirsoft\Gdpr\Http\Resources;
|
||||
|
||||
use App\Http\Resources\BaseApiResource;
|
||||
use Illuminate\Http\Request;
|
||||
use Plugins\Sirsoft\Gdpr\Services\CookieCategoryService;
|
||||
use Plugins\Sirsoft\Gdpr\Services\GdprConsentService;
|
||||
|
||||
/**
|
||||
* GDPR 사용자 현재 동의 상태 API 리소스
|
||||
*
|
||||
* `gdpr_user_consents` (status, mutable) 단일 레코드를 응답 형식으로 변환.
|
||||
* 회원의 활성/철회 상태를 마이페이지·로그인 직후 동기화에 노출합니다.
|
||||
*
|
||||
* `consent_label` 은 카탈로그(쿠키 카테고리) 다국어 라벨을 현재 locale 기준으로 변환한 값으로,
|
||||
* 마이페이지 「내 동의 현황」 에서 raw key (cookie_analytics) 대신 사람 친화 표기를 노출하기 위함.
|
||||
*
|
||||
* `needs_renewal_this_item` 은 *선택형 항목 중 정책 버전이 옛 버전인* 행에서 true — 마이페이지
|
||||
* 액션 컬럼이 "다시 동의" 대신 "최신 정책으로 갱신" 분기를 표시할 때 사용 (#21).
|
||||
*/
|
||||
class GdprUserConsentResource extends BaseApiResource
|
||||
{
|
||||
/**
|
||||
* 리소스를 배열로 변환합니다.
|
||||
*
|
||||
* @param Request $request HTTP 요청
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
$categoryService = app(CookieCategoryService::class);
|
||||
$consentService = app(GdprConsentService::class);
|
||||
$consentKey = (string) $this->consent_key;
|
||||
$isRequired = $categoryService->isRequired($consentKey);
|
||||
$isConsented = (bool) $this->is_consented;
|
||||
$currentPolicyVersion = $consentService->getCurrentPolicyVersion();
|
||||
$policyVersion = (string) ($this->policy_version ?? '');
|
||||
// 선택형 항목 중 정책 버전이 옛 버전인지 — 필수는 ePrivacy Art.5(3) 면제로 갱신 대상 아님.
|
||||
$needsRenewalThisItem = ! $isRequired && $isConsented && $policyVersion !== '' && $policyVersion !== $currentPolicyVersion;
|
||||
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'consent_key' => $consentKey,
|
||||
'consent_label' => $categoryService->getLabelForKey($consentKey),
|
||||
'consent_description' => $categoryService->getDescriptionForKey($consentKey),
|
||||
'consent_category' => $this->consent_category,
|
||||
'is_required' => $isRequired,
|
||||
'is_consented' => $isConsented,
|
||||
// Art.7(3) 대칭성 + ePrivacy Art.5(3) 동의 면제 패턴 — 필수 카테고리는 철회/재동의 불가, 선택형만 양방향.
|
||||
'can_revoke' => ! $isRequired && $isConsented,
|
||||
// 활성 동의 + 옛 버전 → 갱신 의도. 활성 동의 + 최신 버전 → 갱신 불요 (이미 최신).
|
||||
// 비활성 (철회 또는 신규) → 다시 동의 (기존 동작).
|
||||
'can_grant' => ! $isRequired && (! $isConsented || $needsRenewalThisItem),
|
||||
'needs_renewal_this_item' => $needsRenewalThisItem,
|
||||
'consented_at' => $this->formatDateTimeStringForUser($this->consented_at),
|
||||
'revoked_at' => $this->formatDateTimeStringForUser($this->revoked_at),
|
||||
'consent_count' => (int) $this->consent_count,
|
||||
'policy_version' => $this->policy_version,
|
||||
'last_source' => $this->last_source,
|
||||
...$this->formatTimestamps(),
|
||||
];
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user