Skip to content

[Feat] 문서 권한 확인 API - #28

Merged
kangcheolung merged 3 commits into
developfrom
feature/24
Jul 16, 2026
Merged

[Feat] 문서 권한 확인 API#28
kangcheolung merged 3 commits into
developfrom
feature/24

Conversation

@kangcheolung

@kangcheolung kangcheolung commented Jul 16, 2026

Copy link
Copy Markdown
Member

🔍️ 작업 내용

✨ 상세 설명

이슈 3에서 만든 PermissionQueryService의 5단계 판단 로직을 외부 API로 처음 노출합니다.
현재 로그인한 사용자가 특정 문서에 대해 읽기·쓰기·관리 권한을 가지고 있는지, 그리고 그 권한이 어떤 경로(OWNER / PUBLIC / USER_CACHE / ROLE / DEPARTMENT)로 부여됐는지 한 번에 확인할 수 있습니다.

설계 결정 — 기존 boolean 메서드는 수정하지 않음

canReadDocument 등 기존 3개 메서드는 CommandService들이 이미 사용 중이므로 반환 타입 변경 없이, checkDocumentPermission() 단일 메서드를 신규 추가하는 방식으로 구현했습니다. 이 메서드 안에서 문서 조회를 1회만 수행하고 read/write/admin 판단과 sources 수집을 한 번에 처리합니다.

응답 예시

{
  "documentId": 10,
  "canRead": true,
  "canWrite": true,
  "canAdmin": false,
  "sources": ["USER_CACHE", "ROLE"]
}

🛠 추후 리팩토링 및 고도화 계획

  • 이슈 5: 컬렉션 관리 API (GET /collections, DELETE /collections/{id} 등) 구현 후 Swagger 전체 흐름 테스트 예정

📸 스크린샷 (선택)

💬 리뷰 요구사항

  • checkDocumentPermission 최악의 경우 쿼리 15회 발생 (캐시 3 + ROLE 6 + DEPT 6) — UI에서 1회성 호출 용도이므로 허용 범위로 판단했는데 의견 부탁드립니다.

Summary by CodeRabbit

  • 새로운 기능

    • 문서별 내 권한을 확인할 수 있는 API를 추가했습니다.
    • 읽기·쓰기·관리 권한과 권한 출처(소유자, 공개, 역할, 부서 등)를 함께 제공합니다.
    • 존재하지 않는 문서 조회 시 명확한 오류를 반환합니다.
  • 테스트

    • 다양한 권한 조합과 권한 없음, 문서 미존재 시나리오를 검증했습니다.

kangcheolung and others added 3 commits July 16, 2026 19:04
…TO 추가

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
…mission 서비스 + 컨트롤러)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
…/DEPT/복수source/denied/예외)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
@coderabbitai

coderabbitai Bot commented Jul 16, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

문서별 현재 사용자 권한 확인 기능을 추가했습니다. 권한 요약 응답과 출처 열거형을 정의하고, 다섯 가지 권한 경로를 계산하는 서비스를 구현했으며, 이를 조회하는 GET 엔드포인트와 단위 테스트를 추가했습니다.

Changes

문서 권한 확인

Layer / File(s) Summary
권한 요약 계약과 판정
src/main/java/com/opensource/docgrid/domain/permission/dto/response/DocumentPermissionSummaryResponse.java, src/main/java/com/opensource/docgrid/domain/permission/enums/PermissionSourceType.java, src/main/java/com/opensource/docgrid/domain/permission/service/query/PermissionQueryService.java, src/test/java/com/opensource/docgrid/domain/permission/service/query/PermissionQueryServiceTest.java
문서 ID, 권한 플래그, 권한 출처 목록을 응답으로 정의하고 OWNER, PUBLIC, USER_CACHE, ROLE, DEPARTMENT 기준의 판정 및 예외·복수 출처 시나리오를 테스트합니다.
현재 사용자 권한 조회 엔드포인트
src/main/java/com/opensource/docgrid/domain/permission/controller/PermissionController.java
GET /permissions/documents/{documentId}/me에서 @CurrentUser와 경로의 문서 ID를 전달해 권한 요약 응답을 반환합니다.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Possibly related issues

  • DocGrid/backend issue 21 — 다섯 단계 문서 권한 평가 로직과 직접적으로 연결됩니다.

Possibly related PRs

  • DocGrid/backend#13: 엔드포인트가 사용하는 @CurrentUser 주입 및 ArgumentResolver 구현과 연결됩니다.
  • DocGrid/backend#19: USER_CACHE 권한 출처가 사용하는 캐시 갱신·회수 로직과 연결됩니다.
  • DocGrid/backend#23: 동일한 PermissionQueryService의 문서 권한 조회 로직과 연결됩니다.

Suggested labels: ✨ Feature

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed 제목이 문서 권한 확인 API 추가라는 핵심 변경을 간결하게 잘 요약합니다.
Description check ✅ Passed 템플릿의 주요 섹션과 Closes 링크, 설계 설명, 리뷰 요구사항이 대부분 포함되어 있습니다.
Linked Issues check ✅ Passed checkDocumentPermission, DTO, 엔드포인트, 소스별·복수 소스 테스트가 이슈 #24의 요구를 충족합니다.
Out of Scope Changes check ✅ Passed 요구 범위 밖의 기능 추가나 무관한 리팩토링은 요약상 보이지 않습니다.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/24

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (2)
src/main/java/com/opensource/docgrid/domain/permission/dto/response/DocumentPermissionSummaryResponse.java (1)

10-17: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

DTO 컬렉션 필드의 완전한 불변성 보장

레코드(record)를 활용한 깔끔한 DTO 설계입니다! 🎉 다만, 주입받는 sources 필드가 가변 리스트(ArrayList)일 수 있어 레코드 외부에서 내부 컬렉션 요소가 임의로 변경될 위험이 있습니다. 컴팩트 생성자를 추가하여 리스트를 불변 객체로 방어적 복사하면 외부 변경에 흔들리지 않는 견고한 불변 객체를 완성할 수 있어요! ✨

As per path instructions, **/dto/**/*.java 파일의 "불변성 - Getter/Setter 남용을 지양하고 고정된 데이터 구조(Java Record 활용 등)로 설계되었는지 확인" 지침을 고려한 제안입니다.

♻️ 불변 리스트 보장을 위한 생성자 추가
 public record DocumentPermissionSummaryResponse(
         `@Schema`(description = "문서 ID") Long documentId,
         `@Schema`(description = "읽기 권한") boolean canRead,
         `@Schema`(description = "쓰기 권한") boolean canWrite,
         `@Schema`(description = "관리 권한") boolean canAdmin,
         `@Schema`(description = "권한 부여 경로 (OWNER/PUBLIC/USER_CACHE/ROLE/DEPARTMENT)") List<PermissionSourceType> sources
 ) {
+    public DocumentPermissionSummaryResponse {
+        sources = (sources != null) ? java.util.List.copyOf(sources) : java.util.List.of();
+    }
 }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@src/main/java/com/opensource/docgrid/domain/permission/dto/response/DocumentPermissionSummaryResponse.java`
around lines 10 - 17, Update the DocumentPermissionSummaryResponse record with a
compact constructor that defensively copies sources into an unmodifiable list,
preserving the existing field values and allowing the collection to be safely
exposed without external mutation.

Source: Path instructions

src/main/java/com/opensource/docgrid/domain/permission/service/query/PermissionQueryService.java (1)

182-247: 🚀 Performance & Scalability | 🔵 Trivial

N개의 권한 검사로 인한 다중 DB 쿼리 최적화 제안

권한 확인 로직이 각 출처별로 아주 꼼꼼하게 잘 구현되었네요! 🚀 하지만 현재 방식은 단계별로 읽기/쓰기/관리 권한을 개별 쿼리(exists...)로 검사하기 때문에, 모든 단계를 거칠 경우 최대 15번의 카운트 쿼리가 발생할 수 있습니다. 당장은 문제없더라도 추후 트래픽이 증가하면 DB 병목 원인이 될 수 있으니, 사용자 ID와 문서 ID를 기반으로 해당 권한 플래그 묶음을 한 번의 쿼리로 가져오도록 Repository 단을 최적화하는 방안을 추후 고려해 보세요.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@src/main/java/com/opensource/docgrid/domain/permission/service/query/PermissionQueryService.java`
around lines 182 - 247, Optimize checkDocumentPermission by replacing the
separate per-permission exists... calls across document and collection
repositories with repository methods that fetch the user/document read, write,
and admin flags in a single query per permission source. Preserve the existing
OWNER, PUBLIC, USER_CACHE, ROLE, DEPARTMENT, source collection, and response
behavior while reducing the maximum number of database queries.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In
`@src/main/java/com/opensource/docgrid/domain/permission/dto/response/DocumentPermissionSummaryResponse.java`:
- Around line 10-17: Update the DocumentPermissionSummaryResponse record with a
compact constructor that defensively copies sources into an unmodifiable list,
preserving the existing field values and allowing the collection to be safely
exposed without external mutation.

In
`@src/main/java/com/opensource/docgrid/domain/permission/service/query/PermissionQueryService.java`:
- Around line 182-247: Optimize checkDocumentPermission by replacing the
separate per-permission exists... calls across document and collection
repositories with repository methods that fetch the user/document read, write,
and admin flags in a single query per permission source. Preserve the existing
OWNER, PUBLIC, USER_CACHE, ROLE, DEPARTMENT, source collection, and response
behavior while reducing the maximum number of database queries.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: d6318160-438d-4eac-9d17-61478cac5ff2

📥 Commits

Reviewing files that changed from the base of the PR and between 3dbbe5c and 7c8b2c4.

📒 Files selected for processing (5)
  • src/main/java/com/opensource/docgrid/domain/permission/controller/PermissionController.java
  • src/main/java/com/opensource/docgrid/domain/permission/dto/response/DocumentPermissionSummaryResponse.java
  • src/main/java/com/opensource/docgrid/domain/permission/enums/PermissionSourceType.java
  • src/main/java/com/opensource/docgrid/domain/permission/service/query/PermissionQueryService.java
  • src/test/java/com/opensource/docgrid/domain/permission/service/query/PermissionQueryServiceTest.java

@kangcheolung
kangcheolung merged commit 8aafcbb into develop Jul 16, 2026
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feat] 문서 권한 확인 API 구현 - checkDocumentPermission

1 participant