Files
Gnuboard7/modules/_bundled/sirsoft-ecommerce/src/Services/ProductReviewImageService.php
T
HeuJung 7b56d5f23a feat(core,board,ecommerce,page,ckeditor5,kginicis): 업로드 이미지 축소·로그인 2단계 인증 도입 + 파생 결함 수정
인터뷰에서 방향만 정하고 남겨 뒀던 후속 5건을 구현하고, 커밋 전 종합 점검에서
발견한 결함 2건을 함께 고쳤다.

기능 도입:
- 업로드 이미지 축소 — `upload.image_max_width` / `image_max_height` / `image_quality`
 는 저장·검증만 되고 리사이즈 코드가 0건이었다. 비율 유지, 상한 이내면 재인코딩하지
 않음(불필요한 화질 손실 방지), 한계 미설정이면 무동작(기존 사이트 이미지 보호).
 PNG·GIF·WebP 투명도 보존. 실패해도 업로드는 계속되고 원본이 저장된다.
- 로그인 2단계 인증 — `security.two_factor_auth` 는 설정 항목만 있고 구현도 화면
 컨트롤도 없었다. 코어 IDV 인프라를 재사용해 purpose `login` 을 추가하고, 비밀번호
 확인 통과 후 challenge 만 발행한다(토큰 미발급 + logout). `POST /api/auth/login/two-factor`
 가 코드를 확인해야 토큰이 나가며, 로그인과 같은 요청 제한을 적용한다. challenge 의
 purpose 를 대조해 다른 흐름의 challenge 로 로그인하는 것을 막는다. 코드 발송이
 실패하면 실패로 알린다 — 2단계를 건너뛰고 로그인시키면 통제가 조용히 열린다.

결함 수정:
- 게시글 수정 시 사용자 경로가 `attachment_ids` 를 Service 로 넘기지 않아, 검증과
 권한은 통과하고 200 을 받는데 첨부만 조용히 연결되지 않았다. 관리자 경로는 넘기고
 있어 같은 요청이 화면에 따라 다르게 동작했다.
- 설정 화면 라디오가 `pointer-events-none` + Label click 으로만 상태를 바꿔, 키보드
 방향키(change) 조작 시 화면 표시와 저장될 값이 어긋났다. 동일 패턴 4개 레이아웃
 12개 라디오에 change 액션을 부여하고 params 를 click 과 동일하게 고정한다.
- 주문완료 화면이 결제수단 확인보다 영수증 조회를 앞세워, PG 를 거치지 않는 주문에서도
 매번 404 요청이 나갔다.
- 개별 게시판 폼의 숫자 항목에 경계값 바인딩이 없어 환경설정 화면과 안내가 달랐다.

커밋 전 점검에서 발견:
- 2단계 인증이 반쪽으로 들어가 있었다. enum 에 case 만 추가하고 코어 purpose
 레지스트리와 ko/en 라벨을 빠뜨려, 목적 목록 API 에서 통째로 빠지고 `hasPurpose`
 가 false 였으며 라벨 대신 i18n 키 원문이 반환됐다. 관리자가 이 목적의 메시지
 템플릿·정책을 만들 수 없는 상태였다. 세 곳을 enum 기준으로 전수 대조하는 회귀
 테스트를 함께 둔다.
- 업로드 이미지 축소가 적용되지 않은 8번째 서비스(레이아웃 편집기 첨부)가 있었다.
 열거형 커버리지 테스트는 내 조사 결과를 green 으로 고정할 뿐 전수를 증명하지
 못한다 — 같은 규약을 조건으로 표현한 audit 룰이 첫 실행에서 검출했다.

재발 방지:
- audit 룰 `upload-service-image-resize` (신규 업로드 서비스의 축소 누락 검출)
- 트러블슈팅 사례 20 (코어 설정이 일부 경로에만 적용되는 증상의 진단 절차)
- `sirsoft-ckeditor5` 의 코어 최소 요구 버전을 7.0.6 으로 상향 (신설 클래스 의존)

공개 이슈: gnuboard/g7
2026-07-30 07:57:06 +09:00

181 lines
5.8 KiB
PHP

<?php
namespace Modules\Sirsoft\Ecommerce\Services;
use App\Contracts\Extension\StorageInterface;
use App\Extension\HookManager;
use App\Support\ImageResizer;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use Modules\Sirsoft\Ecommerce\Exceptions\ReviewImageUploadLimitException;
use Modules\Sirsoft\Ecommerce\Models\ProductReview;
use Modules\Sirsoft\Ecommerce\Models\ProductReviewImage;
use Modules\Sirsoft\Ecommerce\Repositories\Contracts\ProductReviewImageRepositoryInterface;
use Symfony\Component\HttpFoundation\StreamedResponse;
/**
* 상품 리뷰 이미지 서비스
*
* 리뷰 이미지 업로드, 삭제 등의 비즈니스 로직을 처리합니다.
*/
class ProductReviewImageService
{
/**
* ProductReviewImageService 생성자
*
* @param StorageInterface $storage 모듈 스토리지 드라이버
* @param EcommerceSettingsService $settingsService 이커머스 설정 서비스
* @param ProductReviewImageRepositoryInterface $repository 리뷰 이미지 리포지토리
*/
public function __construct(
protected StorageInterface $storage,
protected EcommerceSettingsService $settingsService,
protected ProductReviewImageRepositoryInterface $repository
) {}
/**
* 리뷰 이미지 업로드
*
* @param UploadedFile $file 업로드된 파일
* @param ProductReview $review 리뷰 모델
* @return ProductReviewImage 생성된 이미지
*
* @throws ReviewImageUploadLimitException 최대 업로드 수 초과 시
*/
public function upload(UploadedFile $file, ProductReview $review): ProductReviewImage
{
$maxImages = (int) $this->settingsService->getSetting(
'review_settings.max_images',
config('ecommerce.review.max_images', 5)
);
$currentCount = $review->images()->count();
if ($currentCount >= $maxImages) {
throw new ReviewImageUploadLimitException($maxImages);
}
HookManager::doAction('sirsoft-ecommerce.review-image.before_upload', $file, $review);
$storedFilename = Str::uuid().'.'.$file->getClientOriginalExtension();
$path = "reviews/{$review->id}/{$storedFilename}";
// 환경설정 > 업로드의 최대 가로/세로·품질 적용 (코어 설정이 모든 업로드 경로에 동일 적용)
app(ImageResizer::class)->resizeInPlace($file->getRealPath(), $file->getMimeType());
$this->storage->put('images', $path, file_get_contents($file->getRealPath()));
$disk = $this->storage->getDisk();
// 이미지 크기 정보 추출
$width = null;
$height = null;
if (str_starts_with($file->getMimeType(), 'image/')) {
$imageSize = @getimagesize($file->getRealPath());
if ($imageSize) {
$width = $imageSize[0];
$height = $imageSize[1];
}
}
$maxSortOrder = $review->images()->max('sort_order') ?? 0;
$image = $this->repository->create([
'review_id' => $review->id,
'original_filename' => $file->getClientOriginalName(),
'stored_filename' => $storedFilename,
'disk' => $disk,
'path' => $path,
'mime_type' => $file->getMimeType(),
'file_size' => $file->getSize(),
'width' => $width,
'height' => $height,
'collection' => 'review',
'sort_order' => $maxSortOrder + 1,
'is_thumbnail' => ($maxSortOrder === 0),
'created_by' => Auth::id(),
]);
Log::info('리뷰 이미지 업로드 완료', [
'image_id' => $image->id,
'review_id' => $review->id,
'original_filename' => $image->original_filename,
]);
HookManager::doAction('sirsoft-ecommerce.review-image.after_upload', $image);
return $image;
}
/**
* 리뷰 이미지 삭제
*
* @param ProductReviewImage $image 이미지 모델
* @return bool 삭제 성공 여부
*/
public function delete(ProductReviewImage $image): bool
{
HookManager::doAction('sirsoft-ecommerce.review-image.before_delete', $image);
if ($this->storage->exists('images', $image->path)) {
$this->storage->delete('images', $image->path);
}
$result = $this->repository->delete($image);
Log::info('리뷰 이미지 삭제 완료', ['image_id' => $image->id]);
HookManager::doAction('sirsoft-ecommerce.review-image.after_delete', $image);
return $result;
}
/**
* 해시로 이미지 조회
*
* @param string $hash 이미지 해시 (12자)
* @return ProductReviewImage|null 이미지 모델 (없으면 null)
*/
public function findByHash(string $hash): ?ProductReviewImage
{
return $this->repository->findByHash($hash);
}
/**
* 이미지 다운로드 응답 생성
*
* @param string $hash 이미지 해시 (12자)
* @return StreamedResponse|null 다운로드 응답 (없으면 null)
*/
public function download(string $hash): ?StreamedResponse
{
$image = $this->findByHash($hash);
if (! $image) {
return null;
}
$response = $this->storage->response(
'images',
$image->path,
$image->original_filename,
[
'Content-Type' => $image->mime_type,
'Cache-Control' => 'public, max-age=31536000',
]
);
if (! $response) {
Log::error('리뷰 이미지 스토리지에 없음', [
'review_image_id' => $image->id,
'path' => $image->path,
]);
return null;
}
return $response;
}
}