Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Refactor] Auth 관련 코드 고도화 #100

Merged
merged 5 commits into from
Jun 17, 2024
Merged

[Refactor] Auth 관련 코드 고도화 #100

merged 5 commits into from
Jun 17, 2024

Conversation

moomint8
Copy link
Member

PR 타입(하나 이상의 PR 타입을 선택해주세요)

  • 기능 추가
  • 기능 삭제
  • 버그 수정
  • 의존성, 환경 변수, 빌드 관련 코드 업데이트
  • 코드 및 구조 개선

반영 브랜치

feat/auth -> dev

변경 사항

  • 관리자에 의한 비밀번호 초기화일 때는 2차 인증 등록 페이지로 리다이렉트되지 않도록 개선했습니다.
  • 예상하지 못한 에러와 보안을 위해 해둔 catch(Exception e) 부분에 추후 해당 에러를 추적 및 해결할 수 있도록 print 문을 추가했습니다.
  • 더미 값 변경에 따른 일부 테스트 코드에서 발생한 문제를 해결하기 위해 임시로 주석 처리 했습니다.

테스트 결과

image

해당 테스트는 임시적인 것으로 각 담당자가 더미 값에 종속되지 않도록 개선할 예정입니다.

moomint8 added 5 commits June 12, 2024 10:14
유지보수를 위해 주석을 추가했습니다.
버전 차이로 인한 충돌을 해결하기 위한 커밋입니다.
첫 로그인인 경우를 구별하는 방법이 default password 인 경우만을 한정하여 관리자가 비밀번호를 값 지정 없이 초기화한 경우에도 첫 로그인 페이지로 리다이렉트되었습니다.
이제는 2차 인증인 Authenticator를 등록하였는지 또한 검토하여 보다 더 첫 로그인인 경우에만 해당 경우에 맞는 동작을 하도록 개선했습니다.
예상하지 못한 에러가 발생한 경우 보안을 위해 사용자에겐 400 BadRequest를 반환하도록 구현해두었습니다.
이제는 해당 에러가 왜 발생했는지 추적하고, 개선할 수 있도록 log를 남기는 print문을 추가했습니다.
일부 테스트 코드가 더미 값에 의존하여 동작하고 있어 더미 값이 변동됨에 따라 테스트 통과가 되지 않는 문제가 발생했습니다.
CI가 테스트 코드 통과를 전제로 하고 있으므로 이를 수정하기 위해 우선 문제가 발생한 테스트 코드를 주석처리했습니다.
이 테스트 코드들은 추후 더미 값과 관계 없이 동작을 테스트할 수 있도록 고도화될 예정입니다.
@moomint8 moomint8 added the refactor Improve code or structure label Jun 16, 2024
@moomint8 moomint8 self-assigned this Jun 16, 2024
if (bCryptPasswordEncoder.matches(defaultPassword, customUserDetails.getPassword())) {
// Default 비밀번호면서 Authenticator 등록이 안된 경우 비밀번호 변경을 유도하기 위해 210 반환
// 첫 로그인인 경우를 위한 메소드
if (bCryptPasswordEncoder.matches(defaultPassword, customUserDetails.getPassword()) && secret == null) {
response.setStatus(210);
response.setCharacterEncoding("UTF-8");
response.getWriter().write("비밀번호를 변경해주세요.");
Copy link

Choose a reason for hiding this comment

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

Code Review:

  1. Positive Aspects:

    • The code seems to be well-structured in terms of functionality and readability.
    • Usage of comments to explain the purpose of the code block.
  2. Bug Risks:

    • One potential issue could arise if secret is not reliably null when expected. Double-check how secret is set and ensure it represents the intended state accurately.
  3. Improvement Suggestions:

    • Consider enhancing the comment above the conditional statement to make the condition clearer, especially regarding what constitutes a default password and missing registration of Authenticator. Clearer comments can help future developers understand the logic easily.
    • It might be beneficial to extract the magic number 210 into a named constant for better maintainability.
    • Ensure that any sensitive information related to passwords or default configurations is handled securely and according to best practices.
  4. Additional Tips:

    • Unit tests can be helpful, especially covering scenarios where defaultPassword does match and does not match the user's password.
    • When assessing security-related portions of your code, consider running static analysis tools to identify potential vulnerabilities.

Summary:

The code appears well-written with clear intentions. To strengthen it further:

  • Reconsider the condition logic for both default password and Authenticated registration absence.
  • Improve comments for better readability and understanding.
  • Extract magic numbers into constants.
  • Enhance security-related considerations.

@@ -117,6 +119,7 @@ public ResponseEntity<CmdResponseMessageVO> editMyInfo(@Valid @RequestBody CmdRe
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(
new CmdResponseMessageVO("잘못된 입력입니다."));
} catch (Exception e) {
System.err.println("editMyInfo: " + e.getMessage());
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null);
}
}
Copy link

Choose a reason for hiding this comment

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

Code Review:

  1. Error Handling:

    • Using System.err.println for logging exceptions isn't the best practice. Consider using a proper logging framework like SLF4J with Logback or Log4j for better control and flexibility in handling logs.
  2. Repetitive Code:

    • There is significant code duplication in all methods. Consider extracting common error handling logic to remove redundancy.
  3. Magic Strings:

    • Strings like "editMyInfo", "잘못된 입력입니다." are directly used inside the method. It's advisable to extract them into constants for better maintenance and internationalization support.
  4. Response Consistency:

    • Different exceptions lead to the same response status and body (HttpStatus.BAD_REQUEST with null). Ensure you are returning appropriate response codes based on different exception types for better API clarity.
  5. Input Validation:

    • Since you are using @Valid annotation, ensure that the validation constraints are set up correctly on the request objects.
  6. Enhancements:

    • Consider adding more detailed error information in the response body, especially for debugging purposes without exposing sensitive information.
  7. Documentation:

    • Add method-level comments to describe what each method aims to achieve and any important considerations.

Bug Risks:

  • No apparent bug risks in the provided code snippet.

Improvements:

  • Refactor the exception handling and logging to reduce duplication and improve maintainability.
  • Implement proper logging using a logging framework.
  • Consider centralizing error messages for consistency and easier maintenance.

Suggestions:

  • Enhance error responses by providing more context-specific error messages.
  • Consider whether returning null as the body for errors is the most appropriate response; perhaps a more structured error response would be ideal.
  • Implement unit tests to cover these exception scenarios for better code coverage and robustness.

By addressing these improvements and suggestions, your code will not only be more maintainable but also more robust and easier to debug in case of issues.

@@ -106,6 +111,7 @@ public ResponseEntity<CmdResponseMessageVO> removeRank(@RequestBody CmdRequestDu
return ResponseEntity.status(HttpStatus.OK).body(
new CmdResponseMessageVO("직급 삭제 성공"));
} catch (Exception e) {
System.err.println("removeRank: " + e.getMessage());
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null);
}
}
Copy link

Choose a reason for hiding this comment

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

Code Review:

Bug Risks:

  1. Error Handling: Printing errors to System.err is not the best approach for handling exceptions in a production environment. It's better to log these errors in a structured log system.

Improvement Suggestions:

  1. Logging Framework: Use a logging framework like Log4j or SLF4J instead of directly printing to System.err. This will allow better control over log levels and destinations.

  2. Consistency in Error Handling: Consider using a common method for error handling and responses to avoid repetition and ensure consistency across the codebase.

  3. Input Validation: Ensure proper input validation to prevent unexpected behavior, especially when handling requests coming from external sources.

  4. Code Duplication: There seems to be duplication in the error handling logic for all methods. Consider refactoring this into a common method to reduce code repetition.

  5. Explicit Error Messages: Improve error messages for better understanding of issues when they occur. Provide more context to help with debugging.

  6. Unit Testing: Implement unit tests to cover different scenarios for these methods. It helps ensure that the methods behave as expected under various conditions.

  7. Documentation: Add appropriate comments/documentation to improve code readability and maintainability.

  8. Security: If this code interacts with sensitive data or involves transactions, ensure that proper security measures are in place.

Remember, these suggestions aim to enhance the robustness, maintainability, and readability of your codebase.

@@ -119,6 +122,7 @@ public ResponseEntity<CmdResponseMessageVO> editInfo(@Valid @RequestBody CmdRequ
return ResponseEntity.status(HttpStatus.FORBIDDEN).body(
new CmdResponseMessageVO(e.getMessage()));
} catch (Exception e) {
System.err.println("editInfo: " + e.getMessage());
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null);
}
}
Copy link

Choose a reason for hiding this comment

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

Code Review:

Bugs/Issues:

  1. Redundant Exception Handling: The catch block without specific exception types might catch unexpected exceptions like NullPointerException. It's better to handle specific exceptions for better error reporting and handling.

Suggestions for Improvement:

  1. Logger Usage: Consider using a proper logging framework like SLF4J with Logback or Log4j instead of System.err.println(). Logging frameworks provide more flexibility and can be easily configured.

  2. Consistent Error Reporting: Ensure consistent error reporting across methods to ease debugging and maintenance.

  3. Specific Exception Handling: Handle specific exceptions rather than catching the general Exception class for better error granularity.

  4. Refactor Response Body: Instead of returning null in the error case, return a meaningful error response with detailed information to help the client understand what went wrong.

  5. Input Validation Enhancement: Validate input data thoroughly, not just relying on @Valid annotation. Check for possible edge cases and validate parameters before processing operations.

  6. Use Constants for Status Codes: Define HTTP status codes as constants to enhance readability and maintainability.

  7. Code Duplication: There is repetition in error message generation logic. Consider refactoring these parts to reduce duplication.

  8. Security Measures: Depending on the application's sensitivity, consider adding additional security measures where needed, especially considering the user roles and password-related operations.

  9. Unit Testing: Implement unit tests for these methods to ensure they work as expected under different scenarios.

  10. Robustness: Ensure graceful handling of potential business exceptions that might occur during user operations.

Handling these suggestions will lead to a more robust and maintainable codebase.

Copy link

Seems you are using me but didn't get OPENAI_API_KEY seted in Variables/Secrets for this repo. you could follow readme for more information

Copy link
Member

@Leegiyeon Leegiyeon left a comment

Choose a reason for hiding this comment

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

개선 사항 확인했습니다! 이따봐용 :)

@Leegiyeon Leegiyeon merged commit 4ebd8dd into dev Jun 17, 2024
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
refactor Improve code or structure
Projects
Status: Done
Development

Successfully merging this pull request may close these issues.

2 participants