Skip to content

MOSU-132 chore: admin role 인가 로직 추가#136

Merged
wlgns12370 merged 1 commit intodevelopfrom
feature/mosu-132
Jul 25, 2025
Merged

MOSU-132 chore: admin role 인가 로직 추가#136
wlgns12370 merged 1 commit intodevelopfrom
feature/mosu-132

Conversation

@wlgns12370
Copy link
Contributor

@wlgns12370 wlgns12370 commented Jul 25, 2025

✨ 구현한 기능

  • admin role 인가 로직 추가

📢 논의하고 싶은 내용

  • x

🎸 기타

  • x

Summary by CodeRabbit

  • New Features

    • Strengthened security across the platform by enforcing role-based access controls on admin and user endpoints.
    • Enhanced authentication requirements for actions such as application submission, event management, exam registration, profile updates, and payment processing.
    • User ID is now automatically injected into relevant endpoints, streamlining user identification and reducing the need for explicit user ID parameters.
  • Refactor

    • Simplified and clarified controller method signatures, replacing explicit user ID request parameters with automatic injection.
    • Improved code readability and maintainability by removing unused code and redundant dependencies.
    • Reformatted and cleaned up internal logic for better clarity without affecting functionality.
  • Style

    • Applied formatting improvements and added logging for better traceability in cryptographic operations.

@coderabbitai
Copy link

coderabbitai bot commented Jul 25, 2025

Caution

Review failed

The pull request is closed.

Walkthrough

This update enforces method-level security across various controllers by adding @PreAuthorize annotations, refactors user identification to use a custom @UserId annotation instead of request parameters or principal objects, and simplifies cryptographic and data mapping logic. No core business logic is altered; changes focus on access control, code clarity, and minor logging improvements.

Changes

File(s) Change Summary
.../infra/kmc/KmcCryptoManager.java Reformatted imports and string construction, reordered field declarations, added logging, and removed comments. No logic changes.
.../infra/kmc/KmcDataMapper.java Simplified class by removing cryptography dependencies and helper methods, reduced constants, and streamlined logging and parsing logic.
.../presentation/admin/AdminApplicationController.java
.../AdminBannerController.java
.../AdminDashboardController.java
.../AdminRecommendationController.java
.../AdminRefundController.java
.../AdminStudentController.java
Added @PreAuthorize("isAuthenticated() and hasRole('ADMIN')") to various admin endpoints to restrict access to authenticated admins only.
.../presentation/application/ApplicationController.java Added @PreAuthorize("isAuthenticated() and hasRole('USER')") to application endpoints for user access control.
.../presentation/event/EventController.java Enabled @PreAuthorize("isAuthenticated() and hasRole('ADMIN')") on event management endpoints.
.../presentation/exam/ExamController.java Added @PreAuthorize("isAuthenticated()") to all exam endpoints, restricting them to authenticated users.
.../presentation/examapplication/ExamApplicationController.java Added @PreAuthorize("isAuthenticated() and hasRole('USER')") and changed user identification from @RequestParam to custom @UserId annotation.
.../presentation/faq/FaqController.java Enabled @PreAuthorize("isAuthenticated() and hasRole('ADMIN')") on FAQ management endpoints.
.../presentation/inquiry/InquiryController.java Added @PreAuthorize for user and admin roles on inquiry and answer endpoints, respectively.
.../presentation/payment/PaymentWidgetController.java Added @PreAuthorize("isAuthenticated() and hasRole('USER')") and refactored user ID acquisition to use @UserId annotation in all methods.
.../presentation/profile/ProfileController.java
.../ProfileControllerDocs.java
Replaced @AuthenticationPrincipal with @UserId for user identification and added @PreAuthorize("isAuthenticated()") to endpoints.
.../presentation/profile/RecommenderController.java Changed user ID parameter from @RequestParam to @UserId and added @PreAuthorize("isAuthenticated()") to methods.
.../presentation/recommendation/RecommendationController.java Changed user ID parameter from @RequestParam to @UserId and added @PreAuthorize("isAuthenticated() and hasRole('USER')") to the create method.

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant Controller
  participant Security
  participant Service

  Client->>Controller: API Request (e.g., POST /apply)
  Controller->>Security: @PreAuthorize check
  alt Authorized
    Security-->>Controller: Access granted
    Controller->>Service: Business logic (with userId from @UserId)
    Service-->>Controller: Result
    Controller-->>Client: Response
  else Not authorized
    Security-->>Client: 403 Forbidden
  end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Suggested labels

우선순위 중

Suggested reviewers

  • jbh010204
  • polyglot-k

Poem

In the warren of code, security grew,
With annotations sprinkled—a PreAuthorize view!
Rabbits hop safely, IDs in their paws,
No more request params, no sneaky flaws.
Refactored and tidy, the controllers now gleam—
A carrot for safety, and code fit for a dream! 🥕

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 384b76a and bc16ee4.

📒 Files selected for processing (19)
  • src/main/java/life/mosu/mosuserver/infra/kmc/KmcCryptoManager.java (2 hunks)
  • src/main/java/life/mosu/mosuserver/infra/kmc/KmcDataMapper.java (1 hunks)
  • src/main/java/life/mosu/mosuserver/presentation/admin/AdminApplicationController.java (3 hunks)
  • src/main/java/life/mosu/mosuserver/presentation/admin/AdminBannerController.java (3 hunks)
  • src/main/java/life/mosu/mosuserver/presentation/admin/AdminDashboardController.java (2 hunks)
  • src/main/java/life/mosu/mosuserver/presentation/admin/AdminRecommendationController.java (2 hunks)
  • src/main/java/life/mosu/mosuserver/presentation/admin/AdminRefundController.java (3 hunks)
  • src/main/java/life/mosu/mosuserver/presentation/admin/AdminStudentController.java (3 hunks)
  • src/main/java/life/mosu/mosuserver/presentation/application/ApplicationController.java (3 hunks)
  • src/main/java/life/mosu/mosuserver/presentation/event/EventController.java (4 hunks)
  • src/main/java/life/mosu/mosuserver/presentation/exam/ExamController.java (3 hunks)
  • src/main/java/life/mosu/mosuserver/presentation/examapplication/ExamApplicationController.java (2 hunks)
  • src/main/java/life/mosu/mosuserver/presentation/faq/FaqController.java (4 hunks)
  • src/main/java/life/mosu/mosuserver/presentation/inquiry/InquiryController.java (5 hunks)
  • src/main/java/life/mosu/mosuserver/presentation/payment/PaymentWidgetController.java (3 hunks)
  • src/main/java/life/mosu/mosuserver/presentation/profile/ProfileController.java (1 hunks)
  • src/main/java/life/mosu/mosuserver/presentation/profile/ProfileControllerDocs.java (3 hunks)
  • src/main/java/life/mosu/mosuserver/presentation/profile/RecommenderController.java (3 hunks)
  • src/main/java/life/mosu/mosuserver/presentation/recommendation/RecommendationController.java (2 hunks)
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feature/mosu-132

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@wlgns12370 wlgns12370 merged commit 26034d8 into develop Jul 25, 2025
1 of 2 checks passed
Copy link

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Summary of Changes

Hello @wlgns12370, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request significantly enhances the application's security posture by implementing robust role-based access control (RBAC) across a wide range of API endpoints. It leverages Spring Security to enforce granular permissions for both 'ADMIN' and 'USER' roles, ensuring that functionalities are accessible only to authorized individuals. Additionally, it includes minor refactorings in the KMC integration module and standardizes user ID handling, contributing to a more secure and maintainable codebase.

Highlights

  • Role-Based Access Control (RBAC): Implemented comprehensive role-based access control across numerous API endpoints using Spring Security's @PreAuthorize annotation. This restricts access to functionalities based on whether a user is authenticated and possesses the 'ADMIN' or 'USER' role.
  • Admin Functionality Security: Secured all administrative endpoints (e.g., managing applications, banners, dashboards, refunds, students, events, FAQs, and answering inquiries) to be accessible only by users with the 'ADMIN' role.
  • User Functionality Security: Ensured user-specific functionalities (e.g., applying for services, viewing applications, managing exam applications, payments, profiles, and recommendations, and creating/deleting inquiries) are accessible only to authenticated users, often specifically requiring the 'USER' role.
  • KMC Integration Refactoring: Refactored KMC (Korea Mobile Certification) related utility classes (KmcCryptoManager, KmcDataMapper) by removing unnecessary decryption logic for CI/DI values and simplifying logging, streamlining the handling of sensitive KMC data.
  • Standardized User ID Retrieval: Standardized user ID retrieval in several controllers by replacing @AuthenticationPrincipal or @RequestParam with a custom @UserId annotation, improving code consistency and simplifying authentication integration.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point in your pull request via creating an issue comment (i.e. comment on the pull request page) using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in issue comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments or fill out our survey to provide feedback.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request adds role-based authorization logic to numerous controller endpoints using Spring Security's @PreAuthorize annotation, which is a great improvement for the application's security. The refactoring to use a custom @UserId annotation is also a positive change for code clarity and consistency.

I've identified a few areas for improvement. Some refactoring has led to the removal of useful Javadocs and comments, which impacts maintainability. More critically, I've found several instances in the PaymentWidgetController where the authenticated user's ID is passed to methods but not used in the underlying service calls. This is a significant security concern that must be addressed to prevent users from performing actions on behalf of others.

Comment on lines 30 to 33
public ApiResponseWrapper<PaymentPrepareResponse> prepare(
@UserId Long userId,
@Valid @RequestBody PreparePaymentRequest request
) {

Choose a reason for hiding this comment

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

high

The userId obtained from the security context is not being used in the paymentService.prepare(request) call. This is a potential security risk. The service layer should use the userId to ensure that the payment is being prepared for the currently authenticated user, preventing one user from initiating actions on behalf of another.

Suggested change
public ApiResponseWrapper<PaymentPrepareResponse> prepare(
@UserId Long userId,
@Valid @RequestBody PreparePaymentRequest request
) {
@PreAuthorize("isAuthenticated() and hasRole('USER')")
public ApiResponseWrapper<PaymentPrepareResponse> prepare(
@UserId Long userId,
@Valid @RequestBody PreparePaymentRequest request
) {
PaymentPrepareResponse response = paymentService.prepare(userId, request);

Comment on lines +45 to +48
@PreAuthorize("isAuthenticated() and hasRole('USER')")
public ApiResponseWrapper<Void> confirm(
@UserId Long userId,
@RequestBody PaymentRequest request

Choose a reason for hiding this comment

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

high

Similar to the prepare method, the userId from the authenticated user is not being used in the paymentService.confirm(request) call. For security, the service method should validate that the user confirming the payment is the one who initiated it. Please pass the userId to the service layer and use it for validation.

Suggested change
@PreAuthorize("isAuthenticated() and hasRole('USER')")
public ApiResponseWrapper<Void> confirm(
@UserId Long userId,
@RequestBody PaymentRequest request
@PreAuthorize("isAuthenticated() and hasRole('USER')")
public ApiResponseWrapper<Void> confirm(
@UserId Long userId,
@RequestBody PaymentRequest request
) {
paymentService.confirm(userId, request);

Comment on lines 42 to 57
public String decryptResponseData(String recCert) {
try {
// 1차 복호화
String firstDecrypted = decrypt(recCert);

// 데이터와 HMAC(무결성 검증 값) 분리
int firstIdx = firstDecrypted.indexOf(DELIMITER);
String encPara = firstDecrypted.substring(0, firstIdx);
String receivedHmac = firstDecrypted.substring(firstIdx + 1, firstDecrypted.lastIndexOf(DELIMITER));

// 무결성 검증
String receivedHmac = firstDecrypted.substring(firstIdx + 1,
firstDecrypted.lastIndexOf(DELIMITER));
String generatedHmac = secuManager.getMsg(encPara);
if (!generatedHmac.equals(receivedHmac)) {
throw new SecurityException("KMC 데이터의 위변조가 의심됩니다.");
}

// 2차 복호화하여 최종 데이터 반환
return decrypt(encPara);
} catch (Exception e) {
throw new RuntimeException("KMC 인증 결과를 처리하는 중 오류가 발생했습니다.", e);
}
}

Choose a reason for hiding this comment

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

medium

The Javadocs and explanatory inline comments for decryptResponseData have been removed. While the code might be clear now, this documentation is very valuable for future maintainers to understand the multi-step decryption and HMAC verification process. Please consider restoring the comments and Javadoc to improve code maintainability.

log.info(" - Name: {}", tokens[NAME_INDEX]);
log.info(" - PhoneNo: {}", tokens[PHONE_NO_INDEX]);
log.info(" - PlusInfo: {}", tokens[PLUS_INFO_INDEX]);
log.info(" - PlusInfo -> {}", tokens[PLUS_INFO_INDEX]);

Choose a reason for hiding this comment

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

medium

This log statement appears to be a duplicate of the one on the previous line and seems like a leftover from debugging. It should be removed to keep the code clean.

Suggested change
log.info(" - PlusInfo -> {}", tokens[PLUS_INFO_INDEX]);
log.info(" - PlusInfo -> {}", tokens[PLUS_INFO_INDEX]);

@wlgns12370 wlgns12370 deleted the feature/mosu-132 branch August 7, 2025 01:41
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.

1 participant