Skip to content

Conversation

@jlhyunii
Copy link
Collaborator

@jlhyunii jlhyunii commented Jun 17, 2025

✨ 작업 개요

게스트 사용자 로그인 API입니다.

✅ 작업 내용

이번 PR에서 작업한 내용을 간략히 설명해주세요.

  • Member 엔티티에 boolean 타입의 isGuest 필드가 추가되어 일반 소셜 로그인의 경우에는 false, 게스트 로그인의 경우 true로 나타납니다. 이를 보고 게스트임을 판단하며 1시간마다, 1시간 이상 된 게스트 계정을 DB에서 삭제합니다.
  • 해당 코드를 pull 받으시면 아마 social_provider와 provider_id가 null이 될 수 없어서 에러가 날텐데, 그건 데이터베이스 설정에서 바꿔주시면 됩니다.
  • 게스트가 삭제될 때 해당 게스트와 연관된 데이터 모두 삭제됩니다.
image image

📌 참고 사항(선택)

💬리뷰 요구사항(선택)

리뷰어가 특별히 봐주었으면 하는 부분이 있다면 작성해주세요.

🔗 관련 이슈

Summary by CodeRabbit

  • New Features

    • Introduced guest user login, allowing users to access the platform as guests via a new public endpoint.
    • Guest accounts are automatically cleaned up every hour to maintain system hygiene.
  • Enhancements

    • Interviews now associate the host as a full member entity, improving host management and permissions.
    • Added new relationships in user profiles for better management of cover letters, resumes, interviews, and hosted sessions.
  • Security

    • Updated access rules to allow guest login without authentication.
    • Guest users are prevented from reissuing tokens for enhanced security.
  • Improvements

    • More robust handling and cleanup of guest accounts.
    • Refined interview and member data structures for improved consistency and maintainability.

@jlhyunii jlhyunii requested a review from zjhj0814 June 17, 2025 14:52
@jlhyunii jlhyunii self-assigned this Jun 17, 2025
@jlhyunii jlhyunii added the ✨ feature New feature or request label Jun 17, 2025
@coderabbitai
Copy link

coderabbitai bot commented Jun 17, 2025

Walkthrough

This update introduces guest user functionality, including guest login, token handling, and scheduled cleanup of expired guest accounts. The Interview entity's host reference is refactored from a primitive ID to a Member association, with related adjustments across converters and services. Additional cascade and orphan removal options are added to several entity relationships.

Changes

File(s) Change Summary
DemoApplication.java Enabled Spring scheduling with @EnableScheduling.
config/auth/GuestAccountCleaner.java Added scheduled component to delete old guest accounts every hour.
config/auth/JwtProvider.java Modified access token generation to include guest status; prevented token reissue for guests.
config/auth/SecurityConfig.java Allowed unauthenticated access to /auth/guest endpoint.
config/auth/controller/OauthController.java Added POST /auth/guest endpoint for guest login.
config/auth/dto/GuestLoginResponse.java Introduced DTO for guest login response.
config/auth/service/OauthService.java Added guest login logic and updated token generation to handle guest status.
converter/InterviewConverter.java Updated logic to use Member entity for host references instead of hostId.
domain/Coverletter.java Added one-to-many relationship to Qna entities.
domain/Interview.java Replaced hostId with host (Member association); added cascading and orphan removal for related entities.
domain/InterviewOption.java Removed cascade from interview association.
domain/Member.java Made provider fields nullable, added guest flag, new entity relationships, and guest factory method.
repository/MemberRepository.java Added method to delete guest members by creation time.
service/interview/InterviewCommandService.java Removed redundant public modifier from interface method.
service/interview/InterviewCommandServiceImpl.java, service/interviewOption/InterviewOptionCommandServiceImpl.java Updated host permission checks to use interview.getHost().getId() instead of getHostId().

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant OauthController
    participant OauthService
    participant MemberRepository
    participant JwtProvider

    Client->>OauthController: POST /auth/guest
    OauthController->>OauthService: loginAsGuest()
    OauthService->>MemberRepository: save(guestMember)
    OauthService->>JwtProvider: generateAccessToken(guestId, true)
    JwtProvider-->>OauthService: accessToken
    OauthService-->>OauthController: GuestLoginResponse
    OauthController-->>Client: ApiResponse<GuestLoginResponse>
Loading
sequenceDiagram
    participant GuestAccountCleaner
    participant MemberRepository

    loop Every hour
        GuestAccountCleaner->>MemberRepository: deleteByIsGuestTrueAndCreatedAtBefore(threshold)
    end
Loading

Possibly related PRs

  • cloudcomputinginha/interview_be#7: Modifies the Interview entity, changing the hostId field to a Member association and introducing new relationships, which this PR further extends and refines.

Suggested reviewers

  • jlhyunii

Poem

A guest hops in, a name anew,
With tokens fresh and logic true.
The host now knows its Member friend,
While old guest bunnies meet their end.
Spring’s scheduler keeps things neat—
In code and fields, a tidy feat!
🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings

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 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.

@zjhj0814
Copy link
Collaborator

@coderabbitai review

@coderabbitai
Copy link

coderabbitai bot commented Jun 17, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 4

🔭 Outside diff range comments (1)
src/main/java/cloudcomputinginha/demo/config/auth/JwtProvider.java (1)

23-34: Extract claim key to a constant & reuse SecretKey

Hard-coding the "isGuest" string everywhere risks typos and makes refactors harder.
Likewise, Keys.hmacShaKeyFor(secretKey.getBytes()) is computed on every call; building the SecretKey once and re-using it avoids repeated Base64 decoding and object creation.

+private static final String CLAIM_IS_GUEST = "isGuest";
+private SecretKey key;
+
+@PostConstruct
+void init() {
+    key = Keys.hmacShaKeyFor(secretKey.getBytes());
+}
...
-               .claim("isGuest", isGuest)
+               .claim(CLAIM_IS_GUEST, isGuest)
-               .signWith(key, SignatureAlgorithm.HS256)
+               .signWith(this.key, SignatureAlgorithm.HS256)
🧹 Nitpick comments (12)
src/main/java/cloudcomputinginha/demo/domain/Coverletter.java (1)

8-10: Unused import list can be trimmed

java.util.ArrayList is needed, but java.util.List is already imported by default when List is referenced later; leaving both is fine but redundant imports might accumulate.
Minor nit – consider organising imports.

src/main/java/cloudcomputinginha/demo/DemoApplication.java (1)

7-12: Optional: customise scheduler thread-pool

@EnableScheduling activates the default single-threaded scheduler.
If multiple tasks (e.g., guest clean-up + other future jobs) will run, consider defining a TaskScheduler bean with a thread pool to avoid blocking jobs from delaying each other.

src/main/java/cloudcomputinginha/demo/service/interview/InterviewCommandServiceImpl.java (1)

139-141: Permission check can be reduced to one DB hit

Calling interview.getHost().getId() issues an extra lazy-load query in most JPA setups.
A lighter alternative is to have the repository expose:

boolean existsByIdAndHost_Id(Long interviewId, Long hostId);

and use it for permission validation before fetching the whole entity. Improves performance on hot paths.

src/main/java/cloudcomputinginha/demo/service/interviewOption/InterviewOptionCommandServiceImpl.java (1)

31-33: Apply the same optimisation as in InterviewCommandServiceImpl

As above, consider replacing the lazy load of host with a repository existence check to avoid an extra select just for the permission guard.

src/main/java/cloudcomputinginha/demo/config/auth/controller/OauthController.java (1)

85-89: Consider surfacing basic observability & rate-limits for the new guest endpoint
/auth/guest will probably be hit far more frequently than social-login because there is no prior credential. You may want to:

  • Add a simple log.info() inside guestLogin() to track usage (helps when you need to distinguish bot abuse from normal traffic).
  • Discuss – with the security config – whether per-IP throttling or a plain @RateLimiter (e.g. Bucket4j) is needed.

The implementation itself looks fine – no blocking issues.

src/main/java/cloudcomputinginha/demo/repository/MemberRepository.java (1)

5-11: Return the deleted-row count for better feedback
deleteByIsGuestTrueAndCreatedAtBefore currently returns void; if you change the return type to long, Spring Data will automatically return the number of rows removed.
That allows the caller (the scheduled cleaner) to log how many guest accounts were purged, which is useful for monitoring and alerting.

-void deleteByIsGuestTrueAndCreatedAtBefore(LocalDateTime threshold);
+long deleteByIsGuestTrueAndCreatedAtBefore(LocalDateTime threshold);
src/main/java/cloudcomputinginha/demo/config/auth/GuestAccountCleaner.java (1)

15-20: Expose scheduling constants & log purge results
Small tweaks improve readability and observability:

+private static final long ONE_HOUR_MILLIS = 60 * 60 * 1000L;

-@Scheduled(fixedDelay = 3600000)
+@Scheduled(fixedDelay = ONE_HOUR_MILLIS)

-memberRepository.deleteByIsGuestTrueAndCreatedAtBefore(threshold);
+long deleted = memberRepository.deleteByIsGuestTrueAndCreatedAtBefore(threshold);
+log.info("Guest cleanup removed {} accounts older than {}", deleted, threshold);

(Requires the repository method to return long – see previous comment.)

src/main/java/cloudcomputinginha/demo/config/auth/dto/GuestLoginResponse.java (1)

8-16: Align DTO Lombok style with the rest of the codebase

Other DTOs use @NoArgsConstructor(access = AccessLevel.PROTECTED) to prevent unwanted instantiation while keeping frameworks happy.
Consider applying the same modifier for consistency:

-@NoArgsConstructor
+@NoArgsConstructor(access = AccessLevel.PROTECTED)

Minor, but it keeps the public API surface minimal.

src/main/java/cloudcomputinginha/demo/converter/InterviewConverter.java (1)

133-144: Repeated equals logic – extract helper

The same mi.getMember().getId().equals(interview.getHost().getId()) predicate appears twice.
Extract to a local boolean or method to avoid duplication and improve readability.

+boolean isHost = mi.getMember().getId().equals(interview.getHost().getId());
 ...
-        .filter(mi -> mi.getMember().getId().equals(interview.getHost().getId()))
+        .filter(mi -> isHost)
 ...
-        .isHost(mi.getMember().getId().equals(interview.getHost().getId()))
+        .isHost(isHost)
src/main/java/cloudcomputinginha/demo/domain/Interview.java (2)

47-48: Remove dead hostId comment

Leaving the legacy hostId line commented invites confusion during future refactors.
Recommend deleting it entirely.


68-74: Eager removal on large collections could hit N+1

cascade = REMOVE, orphanRemoval = true on memberInterviews triggers individual delete for each child.
If interviews can have many participants, consider batching or using @OnDelete to let the DB handle cascading deletes.

src/main/java/cloudcomputinginha/demo/domain/Member.java (1)

38-42: Consider explicitly marking nullable columns and documenting rationale

socialProvider and providerId are now nullable to accommodate guest accounts.
That is perfectly valid, but it is worth adding:

@Column(length = 10, nullable = true)  // explain: nullable for guest accounts

so the intent is crystal-clear to future readers. JPA defaults to nullable = true, yet being explicit avoids accidental regressions when someone later adds a global rule to flag “implicit nullable”.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 5e127f9 and 508640b.

📒 Files selected for processing (16)
  • src/main/java/cloudcomputinginha/demo/DemoApplication.java (1 hunks)
  • src/main/java/cloudcomputinginha/demo/config/auth/GuestAccountCleaner.java (1 hunks)
  • src/main/java/cloudcomputinginha/demo/config/auth/JwtProvider.java (2 hunks)
  • src/main/java/cloudcomputinginha/demo/config/auth/SecurityConfig.java (1 hunks)
  • src/main/java/cloudcomputinginha/demo/config/auth/controller/OauthController.java (2 hunks)
  • src/main/java/cloudcomputinginha/demo/config/auth/dto/GuestLoginResponse.java (1 hunks)
  • src/main/java/cloudcomputinginha/demo/config/auth/service/OauthService.java (4 hunks)
  • src/main/java/cloudcomputinginha/demo/converter/InterviewConverter.java (3 hunks)
  • src/main/java/cloudcomputinginha/demo/domain/Coverletter.java (2 hunks)
  • src/main/java/cloudcomputinginha/demo/domain/Interview.java (3 hunks)
  • src/main/java/cloudcomputinginha/demo/domain/InterviewOption.java (1 hunks)
  • src/main/java/cloudcomputinginha/demo/domain/Member.java (3 hunks)
  • src/main/java/cloudcomputinginha/demo/repository/MemberRepository.java (1 hunks)
  • src/main/java/cloudcomputinginha/demo/service/interview/InterviewCommandService.java (1 hunks)
  • src/main/java/cloudcomputinginha/demo/service/interview/InterviewCommandServiceImpl.java (1 hunks)
  • src/main/java/cloudcomputinginha/demo/service/interviewOption/InterviewOptionCommandServiceImpl.java (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
src/main/java/cloudcomputinginha/demo/config/auth/dto/GuestLoginResponse.java (1)
src/main/java/cloudcomputinginha/demo/web/dto/InterviewResponseDTO.java (1)
  • Builder (12-19)
🔇 Additional comments (7)
src/main/java/cloudcomputinginha/demo/config/auth/SecurityConfig.java (1)

73-75: Confirm public exposure of the guest-login endpoint

/auth/guest is now publicly accessible. Double-check that:

  1. The controller mapping path exactly matches this string (case-sensitive).
  2. No additional sub-paths (e.g. /auth/guest/**) are required; otherwise you may need a wildcard to avoid 403s on nested routes.

Nothing blocking, just a verification point.

src/main/java/cloudcomputinginha/demo/domain/InterviewOption.java (1)

43-44: Cascade removal is now handled on the owning side – looks good
Removing cascade = CascadeType.ALL here prevents accidental propagation from InterviewOption to Interview.
Given that Interview now owns the relationship with cascade = REMOVE & orphanRemoval = true, lifecycle rules remain intact.

src/main/java/cloudcomputinginha/demo/service/interview/InterviewCommandService.java (1)

12-13: Redundant public removed – correct for interface methods
Java interface methods are implicitly public; dropping the keyword keeps the code concise and idiomatic.

src/main/java/cloudcomputinginha/demo/config/auth/JwtProvider.java (1)

70-83: Race-condition on refresh-token overwrite

member.setRefreshToken(newRefreshToken) happens after we already validated the saved token.
If two parallel re-issue requests pass validation at the same time, the second update will silently overwrite the first one and both clients will hold valid token pairs.

Mitigate by synchronising on the member row (optimistic lock/version column) or performing an atomic update via UPDATE … WHERE refresh_token = :oldToken.
Alternatively, return HTTP 409 on concurrent refresh attempts.

src/main/java/cloudcomputinginha/demo/config/auth/service/OauthService.java (1)

56-57: 👍 Explicitly passing false clarifies intent

Calling generateAccessToken(member.getId(), false) makes the non-guest assumption explicit—good change.

src/main/java/cloudcomputinginha/demo/converter/InterviewConverter.java (1)

48-51: Builder now sets host – verify missing mandatory fields

Interview.builder().host(member) is added, but the builder still sets currentParticipants = 1 by default.
Make sure caller increments currentParticipants only after MemberInterview is persisted, otherwise host may be counted twice.

src/main/java/cloudcomputinginha/demo/domain/Member.java (1)

47-58: Cascade-REMOVE everywhere may be too aggressive

Every one-to-many collection now uses cascade = CascadeType.REMOVE, orphanRemoval = true.
While this is required for scheduled guest purges, it also means that any deletion of a normal member will hard-delete all related entities.

  1. Do we really intend to wipe résumés / interviews when a regular user deletes their account?
  2. In case GDPR “right to be forgotten” is the goal, that’s fine – but then we probably also need to cascade to other entities (comments, likes, etc.) for consistency.

If the behaviour should be limited to guest cleanup only, consider performing manual deletes in the cleaner rather than globally cascading.

Comment on lines +26 to +28
@OneToMany(mappedBy = "coverletter", cascade = CascadeType.ALL, orphanRemoval = true)
private List<Qna> qnas = new ArrayList<>();

Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Ensure non-null qnas when using Lombok builder

When the entity is created through Lombok’s @Builder, the qnas field will be null unless explicitly set, because new ArrayList<>() is only executed on field initialisation, not in the builder.
Add @Builder.Default to guarantee an empty list and prevent NPEs when business logic calls coverletter.getQnas().

-    @OneToMany(mappedBy = "coverletter", cascade = CascadeType.ALL, orphanRemoval = true)
-    private List<Qna> qnas = new ArrayList<>();
+    @OneToMany(mappedBy = "coverletter", cascade = CascadeType.ALL, orphanRemoval = true)
+    @Builder.Default
+    private List<Qna> qnas = new ArrayList<>();
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
@OneToMany(mappedBy = "coverletter", cascade = CascadeType.ALL, orphanRemoval = true)
private List<Qna> qnas = new ArrayList<>();
@OneToMany(mappedBy = "coverletter", cascade = CascadeType.ALL, orphanRemoval = true)
@Builder.Default
private List<Qna> qnas = new ArrayList<>();
🤖 Prompt for AI Agents
In src/main/java/cloudcomputinginha/demo/domain/Coverletter.java around lines 26
to 28, the qnas list is initialized with new ArrayList<>() but when using
Lombok's @Builder, this initialization is bypassed causing qnas to be null. To
fix this, add the @Builder.Default annotation to the qnas field to ensure it is
initialized to an empty list by default when the builder is used, preventing
potential NullPointerExceptions.

Comment on lines +78 to +87
// 게스트 사용자
public GuestLoginResponse loginAsGuest() {
String name = "게스트" + new Random().nextInt(10000);
Member guest = Member.createGuest(name);
memberRepository.save(guest);

String accessToken = jwtProvider.generateAccessToken(guest.getId(), true);

return new GuestLoginResponse(accessToken, guest.getId(), guest.getName());
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Use SecureRandom + transactional save for guest creation

  1. Random isn’t cryptographically strong. SecureRandom prevents predictable guest names.
  2. No transaction → if token generation fails after persisting, the orphan guest remains. Annotate with @Transactional (or handle rollback manually).
  3. Capture the returned entity from save for clarity.
-String name = "게스트" + new Random().nextInt(10_000);
-Member guest = Member.createGuest(name);
-memberRepository.save(guest);
+String name = "게스트" + new SecureRandom().nextInt(10_000);
+Member guest = memberRepository.save(Member.createGuest(name));
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// 게스트 사용자
public GuestLoginResponse loginAsGuest() {
String name = "게스트" + new Random().nextInt(10000);
Member guest = Member.createGuest(name);
memberRepository.save(guest);
String accessToken = jwtProvider.generateAccessToken(guest.getId(), true);
return new GuestLoginResponse(accessToken, guest.getId(), guest.getName());
}
// 게스트 사용자
public GuestLoginResponse loginAsGuest() {
String name = "게스트" + new SecureRandom().nextInt(10_000);
Member guest = memberRepository.save(Member.createGuest(name));
String accessToken = jwtProvider.generateAccessToken(guest.getId(), true);
return new GuestLoginResponse(accessToken, guest.getId(), guest.getName());
}
🤖 Prompt for AI Agents
In src/main/java/cloudcomputinginha/demo/config/auth/service/OauthService.java
around lines 78 to 87, replace the use of java.util.Random with
java.security.SecureRandom to generate the guest name for stronger randomness.
Annotate the loginAsGuest method with @Transactional to ensure the guest
creation and token generation occur atomically, preventing orphan guest records
if token generation fails. Also, capture and use the entity returned from
memberRepository.save for clarity and consistency.

Comment on lines +53 to +56
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "host_id", nullable = false)
private Member host;

Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Missing @OnDelete may leave orphan FK rows in DB

@ManyToOne with cascade = REMOVE on the parent side is fine, but deleting a Member will currently fail due to FK constraint on Interview.host_id.
Add @OnDelete(action = OnDeleteAction.CASCADE) (Hibernate) or handle manually in service layer.

🤖 Prompt for AI Agents
In src/main/java/cloudcomputinginha/demo/domain/Interview.java around lines 53
to 56, the @ManyToOne relationship to Member as host lacks the @OnDelete
annotation, causing foreign key constraint failures when deleting a Member. To
fix this, add @OnDelete(action = OnDeleteAction.CASCADE) to the host field to
ensure that deleting a Member cascades and removes related Interview entries,
preventing orphaned foreign key rows.

Comment on lines +78 to +86
private boolean isGuest;

public static Member createGuest(String randomName) {
Member member = new Member();
member.email = "guest_" + UUID.randomUUID().toString().substring(0, 5)+ "@guest.com";
member.name = randomName;
member.isGuest = true;
return member;
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add column annotation & reduce collision risk in guest email generation

  1. Persistence:

    @Column(nullable = false)
    private boolean isGuest;

    Even though a primitive boolean is non-null at JVM level, some dialects still generate a nullable column if nullable isn’t set.

  2. Collision risk: 5 random chars give 1.0M combinations → not huge at scale.
    Switching to 8–10 chars is safer and still keeps the email under the 30-char limit:

-member.email = "guest_" + UUID.randomUUID().toString().substring(0, 5) + "@guest.com";
+member.email = "guest_" + UUID.randomUUID().toString().substring(0, 10) + "@guest.com";
🤖 Prompt for AI Agents
In src/main/java/cloudcomputinginha/demo/domain/Member.java around lines 78 to
86, add the @Column(nullable = false) annotation to the isGuest field to ensure
the database column is non-nullable. Also, increase the substring length in the
UUID used for generating the guest email from 5 to between 8 and 10 characters
to reduce collision risk while keeping the email length reasonable.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

✨ feature New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants