Files
Gnuboard7/modules/_bundled/sirsoft-board/src/Traits/ChecksBoardPermission.php
T
HeuJung 41fe812f2c perf(board): 목록·검색·상세의 중복 실행 제거 및 상한 계약 소비
검색 — 이 코어에 추가한 BOOLEAN MODE 정제기가 게시판에는 도달하지 않아
원문 키워드가 그대로 바인딩되고 있었다. + - * " < > 를 넣으면 오류 화면이 떴다.
코어 정제기 경유로 옮겼고, 같은 술어를 count 와 get 으로 두 번 실행하던 것을
페이지네이터 한 번으로 합쳤다. 구체 엔진 직접 호출도 해석기 경유로 바꿔 플러그인
검색엔진이 게시글·신고 검색에 적용된다.

상세 — 같은 글을 3회, 같은 게시판을 5회 읽고 있었다. 조회한 인스턴스를 넘겨
글 1회·게시판 1회로 줄였고, 조회수 증가를 권한 확인 뒤로 옮겨 열람 권한이 없는
요청이 조회수를 올리지 않게 했다.

목록 — 답변 트리의 무제한 조회에 상한과 순환 가드를 두고, O(n²) 병합을 한 패스로
바꿨다. 댓글도 무제한 조회에 상한을 두되 잘렸다는 사실과 전체 건수를 함께 알린다.
조용히 잘리면 "댓글이 그만큼뿐" 으로 보인다. 원댓글 단위 페이지네이션을 더해
답글이 부모와 떨어지지 않게 했다.

관리자 화면 — 총 건수가 잘린 목록에서 페이저가 "1페이지뿐" 으로 접히던 자리를
고쳤다. 저장소가 상한을 붙인 목록인데 화면이 그 값을 1 로 채우고 있어, 기록이
상한을 넘으면 2페이지에 도달할 방법이 없었다.

같은 파일에서 드러난 사전 결함도 함께 처리했다 — 반복 렌더 안의 정적 HTML id,
Icon 의 박스 크기 지정, 단색 버튼의 다크 모드 대비.
2026-08-06 11:13:51 +09:00

177 lines
6.4 KiB
PHP

<?php
namespace Modules\Sirsoft\Board\Traits;
use App\Enums\PermissionType;
use App\Http\Middleware\PermissionMiddleware;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Auth;
use Modules\Sirsoft\Board\Support\BoardPermissionCacheKeys;
/**
* 게시판 권한 체크 Trait
*
* PermissionMiddleware를 내부적으로 호출하여 권한을 체크합니다.
* 미들웨어 로직 변경 시 자동으로 동일하게 동작합니다.
*/
trait ChecksBoardPermission
{
/**
* 게시판 권한을 확인합니다.
*
* @param string $slug 게시판 슬러그
* @param string $action 권한 액션 (예: 'admin.posts.read')
* @param PermissionType $type 권한 타입
*/
protected function checkBoardPermission(string $slug, string $action, PermissionType $type = PermissionType::Admin): bool
{
return $this->checkPermissionViaMiddleware("sirsoft-board.{$slug}.{$action}", $type);
}
/**
* 게시판 복수 권한을 확인합니다. (기본: OR 조건)
*
* @param string $slug 게시판 슬러그
* @param array $actions 권한 액션 배열
* @param PermissionType $type 권한 타입
* @param bool $requireAll 모든 권한 필요 여부
*/
protected function checkBoardPermissions(string $slug, array $actions, PermissionType $type = PermissionType::Admin, bool $requireAll = false): bool
{
$permissions = implode('|', array_map(fn ($action) => "sirsoft-board.{$slug}.{$action}", $actions));
return $this->checkPermissionViaMiddleware($permissions, $type, $requireAll);
}
/**
* 모듈 레벨 권한을 확인합니다.
*
* @param string $resource 리소스명 (예: 'boards')
* @param string $action 권한 액션 (예: 'create')
* @param PermissionType $type 권한 타입
*/
protected function checkModulePermission(string $resource, string $action, PermissionType $type = PermissionType::Admin): bool
{
return $this->checkPermissionViaMiddleware("sirsoft-board.{$resource}.{$action}", $type);
}
/**
* 게시판 권한 확인 후 실패 시 403 반환합니다.
*
* @param string $slug 게시판 슬러그
* @param string $action 권한 액션
* @param PermissionType $type 권한 타입
*/
protected function authorizeOrFail(string $slug, string $action, PermissionType $type = PermissionType::Admin): ?JsonResponse
{
if (! $this->checkBoardPermission($slug, $action, $type)) {
return $this->forbidden('sirsoft-board::messages.permission.denied');
}
return null;
}
/**
* 게시판 복수 권한 확인 후 실패 시 403 반환합니다.
*
* @param string $slug 게시판 슬러그
* @param array $actions 권한 액션 배열
* @param PermissionType $type 권한 타입
* @param bool $requireAll 모든 권한 필요 여부
*/
protected function authorizeAnyOrFail(string $slug, array $actions, PermissionType $type = PermissionType::Admin, bool $requireAll = false): ?JsonResponse
{
if (! $this->checkBoardPermissions($slug, $actions, $type, $requireAll)) {
return $this->forbidden('sirsoft-board::messages.permission.denied');
}
return null;
}
/**
* 모듈 레벨 권한 확인 후 실패 시 403 반환합니다.
*
* @param string $resource 리소스명
* @param string $action 권한 액션
* @param PermissionType $type 권한 타입
*/
protected function authorizeModuleOrFail(string $resource, string $action, PermissionType $type = PermissionType::Admin): ?JsonResponse
{
if (! $this->checkModulePermission($resource, $action, $type)) {
return $this->forbidden('sirsoft-board::messages.permission.denied');
}
return null;
}
/**
* 권한 식별자로 직접 권한을 확인합니다.
*
* Admin/User 페이지에 따라 자동으로 권한 타입을 결정합니다.
*
* @param string $identifier 권한 식별자 (예: 'sirsoft-board.notice.posts.read')
*/
protected function checkPermissionByIdentifier(string $identifier): bool
{
// 권한 타입 자동 결정: admin. 포함 시 Admin, 아니면 User
$type = str_contains($identifier, '.admin.') ? PermissionType::Admin : PermissionType::User;
return $this->checkPermissionViaMiddleware($identifier, $type);
}
/**
* 권한 캐시를 초기화합니다.
*
* 테스트 환경에서 동일 Request 인스턴스가 재사용되는 경우 호출합니다.
*/
public static function clearPermissionCache(): void
{
request()->attributes->remove(BoardPermissionCacheKeys::PERMISSION);
request()->attributes->remove(BoardPermissionCacheKeys::ABILITIES);
}
/**
* PermissionMiddleware를 통해 권한을 확인합니다.
*
* 동일 요청 내에서 같은 권한 조합에 대한 결과를 캐싱합니다.
* 캐시는 request()->instance()를 키로 사용하여 요청 단위로 자동 격리됩니다.
*
* @param string $permission 권한 식별자 (파이프로 복수 권한 구분)
* @param PermissionType $type 권한 타입
* @param bool $requireAll 모든 권한 필요 여부
*/
protected function checkPermissionViaMiddleware(string $permission, PermissionType $type, bool $requireAll = true): bool
{
$request = request();
$userId = Auth::id() ?? 'guest';
$cacheKey = $userId.'|'.$permission.'|'.$type->value.'|'.($requireAll ? '1' : '0');
// 요청 인스턴스에 권한 캐시를 저장하여 요청 단위로 자동 격리
$cache = $request->attributes->get(BoardPermissionCacheKeys::PERMISSION, []);
if (isset($cache[$cacheKey])) {
return $cache[$cacheKey];
}
$middleware = app(PermissionMiddleware::class);
$passed = false;
$middleware->handle(
$request,
function () use (&$passed) {
$passed = true;
return response('ok');
},
$type->value,
$permission,
$requireAll ? 'true' : 'false'
);
$cache[$cacheKey] = $passed;
$request->attributes->set(BoardPermissionCacheKeys::PERMISSION, $cache);
return $passed;
}
}