Skip to content

Prevent login if user is disabled #3509

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

Open
wants to merge 3 commits into
base: develop
Choose a base branch
from
Open

Conversation

CarsonF
Copy link
Member

@CarsonF CarsonF commented Jun 20, 2025

No description provided.

Copy link

coderabbitai bot commented Jun 20, 2025

📝 Walkthrough

Walkthrough

The changes introduce a new authentication exception hierarchy and refactor existing exceptions accordingly. Authentication logic is updated to handle disabled users, including immediate session invalidation upon user disablement. Repositories are updated to return user status with password hash, and related methods are renamed. A new event handler ensures disabled users are logged out. Tests are added to verify disabled user behavior.

Changes

File(s) Change Summary
src/common/exceptions/unauthenticated.exception.ts Added abstract AuthenticationException (extends ClientException), refactored UnauthenticatedException to extend it.
src/core/authentication/authentication.gel.repository.ts
src/core/authentication/authentication.repository.ts
Renamed getPasswordHash to getInfoForLogin, updated to return password hash and user status; added deactivateAllSessions method.
src/core/authentication/authentication.module.ts Added DisablingUserLogsThemOutHandler to providers.
src/core/authentication/authentication.service.ts Login now checks user status; throws UserDisabledException if disabled; added logoutByUser method and exception class.
src/core/authentication/handlers/disabling-user-logs-them-out.handler.ts Added new event handler to log out users when their status changes to 'Disabled'.
test/authentication.e2e-spec.ts Added tests for disabled user behavior, including immediate logout and failed login attempts.
test/utility/login.ts Changed LoginDoc from module-private to exported constant.
test/utility/create-session.ts Extracted and exported CurrentUserDoc GraphQL query constant used in session-related tests.

📜 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 cd16a3a and 930dba2.

📒 Files selected for processing (3)
  • test/authentication.e2e-spec.ts (2 hunks)
  • test/utility/create-session.ts (1 hunks)
  • test/utility/login.ts (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • test/utility/create-session.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • test/utility/login.ts
  • test/authentication.e2e-spec.ts
⏰ Context from checks skipped due to timeout of 90000ms (12)
  • GitHub Check: E2E Tests (neo4j 3/6)
  • GitHub Check: E2E Tests (neo4j 6/6)
  • GitHub Check: lint
  • GitHub Check: E2E Tests (neo4j 4/6)
  • GitHub Check: E2E Tests (neo4j 2/6)
  • GitHub Check: E2E Tests (neo4j 1/6)
  • GitHub Check: E2E Tests (neo4j 5/6)
  • GitHub Check: Generate (base)
  • GitHub Check: Generate (head)
  • GitHub Check: Clean
  • GitHub Check: Unit
  • GitHub Check: Analyze (javascript)
✨ 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.

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: 0

🧹 Nitpick comments (1)
src/core/authentication/handlers/disabling-user-logs-them-out.handler.ts (1)

1-13: Well-implemented event handler with minor suggestion.

The handler correctly listens for UserUpdatedEvent and triggers logout when a user is disabled. The implementation follows NestJS patterns properly.

Consider adding error handling around the logoutByUser call to prevent the handler from failing silently if the logout operation encounters issues:

 async handle({ input, updated: user }: UserUpdatedEvent) {
   if (input.status === 'Disabled') {
-    await this.auth.logoutByUser(user.id);
+    try {
+      await this.auth.logoutByUser(user.id);
+    } catch (error) {
+      // Log error but don't rethrow to avoid preventing user status update
+      console.error('Failed to logout disabled user:', error);
+    }
   }
 }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 6cdf774 and cd16a3a.

📒 Files selected for processing (8)
  • src/common/exceptions/unauthenticated.exception.ts (1 hunks)
  • src/core/authentication/authentication.gel.repository.ts (2 hunks)
  • src/core/authentication/authentication.module.ts (2 hunks)
  • src/core/authentication/authentication.repository.ts (3 hunks)
  • src/core/authentication/authentication.service.ts (4 hunks)
  • src/core/authentication/handlers/disabling-user-logs-them-out.handler.ts (1 hunks)
  • test/authentication.e2e-spec.ts (2 hunks)
  • test/utility/login.ts (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (4)
test/utility/login.ts (1)
src/graphql.ts (1)
  • graphql (6-18)
src/core/authentication/authentication.gel.repository.ts (1)
src/common/id-field.ts (1)
  • ID (24-25)
src/common/exceptions/unauthenticated.exception.ts (1)
src/common/exceptions/exception.ts (1)
  • ClientException (16-16)
src/core/authentication/authentication.repository.ts (2)
src/core/database/query/matching.ts (1)
  • ACTIVE (33-33)
src/common/id-field.ts (1)
  • ID (24-25)
⏰ Context from checks skipped due to timeout of 90000ms (12)
  • GitHub Check: E2E Tests (neo4j 1/6)
  • GitHub Check: E2E Tests (neo4j 4/6)
  • GitHub Check: E2E Tests (neo4j 6/6)
  • GitHub Check: E2E Tests (neo4j 5/6)
  • GitHub Check: E2E Tests (neo4j 2/6)
  • GitHub Check: E2E Tests (neo4j 3/6)
  • GitHub Check: Unit
  • GitHub Check: lint
  • GitHub Check: Generate (base)
  • GitHub Check: Generate (head)
  • GitHub Check: Clean
  • GitHub Check: Analyze (javascript)
🔇 Additional comments (18)
test/utility/login.ts (1)

11-11: LGTM! Good refactoring for test reusability.

Exporting LoginDoc enables its reuse in other test files, which is exactly what's needed for the new authentication tests.

src/core/authentication/authentication.module.ts (2)

9-9: LGTM! Proper import for the new event handler.

The import correctly references the new event handler that will manage disabled user logout.


43-43: LGTM! Correct provider registration.

The handler is properly registered as a provider, enabling it to listen for user update events and trigger logout when users are disabled.

test/authentication.e2e-spec.ts (2)

12-14: LGTM! Proper imports for the new test functionality.

The imports correctly reference the utility functions needed for the disabled user test case.


122-159: Excellent test coverage for disabled user behavior.

This test comprehensively verifies the disabled user feature:

  • Confirms user is initially logged in after registration
  • Disables the user and verifies immediate logout
  • Confirms login prevention with proper error message and codes

The test flow matches the expected behavior and provides good coverage for both the logout trigger and login prevention aspects.

src/core/authentication/authentication.service.ts (6)

5-5: LGTM! Proper import for the new exception hierarchy.

The import correctly adds the new AuthenticationException base class.


77-77: Good enhancement to fetch comprehensive user information.

Changing from getPasswordHashByEmail to getInfoForLogin allows the service to access both password hash and user status in a single repository call, which is more efficient.


79-79: LGTM! Updated to use the new info structure.

The password verification correctly uses the passwordHash from the new info object structure.


82-84: Excellent security implementation for disabled user check.

The logic correctly:

  1. Verifies the password first (preventing information disclosure)
  2. Only then checks if the user is disabled
  3. Throws a specific exception for disabled users

This approach prevents timing attacks and maintains proper security practices.


105-107: Well-implemented programmatic logout method.

The logoutByUser method provides the necessary functionality for the event handler to log out users when they're disabled. The implementation delegates to the repository appropriately.


164-168: Proper exception implementation for disabled users.

The UserDisabledException correctly extends AuthenticationException and provides a clear, specific error message. This allows clients to handle disabled user scenarios appropriately.

src/core/authentication/authentication.gel.repository.ts (2)

67-78: LGTM! Method rename and enhanced return data align with disabled user requirements.

The method rename from getPasswordHash to getInfoForLogin accurately reflects its expanded functionality. The query now correctly returns both passwordHash and status from the Auth.Identity table, which enables the authentication service to check user status during login.


284-296: Well-implemented session deactivation for disabled users.

The new deactivateAllSessions method correctly nullifies the user field on all sessions for a given user, effectively logging them out. The implementation properly uses the typed ID<'User'> parameter and follows the established query pattern.

src/common/exceptions/unauthenticated.exception.ts (2)

4-9: Excellent exception hierarchy design.

The new abstract AuthenticationException base class provides a clean foundation for all authentication-related exceptions with consistent HTTP 401 status. This design supports the addition of specific authentication exceptions like UserDisabledException while maintaining consistency.


11-18: Clean refactoring maintains backward compatibility.

The UnauthenticatedException refactoring to extend AuthenticationException maintains its existing behavior while fitting into the new exception hierarchy. The specific documentation clearly distinguishes this from other authentication exceptions.

src/core/authentication/authentication.repository.ts (3)

5-5: Appropriate import for enhanced user status handling.

The UserStatus import supports the expanded getInfoForLogin method functionality to return user status alongside password hash.


101-129: Robust query implementation for user info retrieval.

The updated getInfoForLogin method correctly implements the complex Cypher query to match email, user, password, and status nodes with active relationships. The structured query builder pattern improves maintainability compared to raw Cypher, and the return type properly reflects both passwordHash and status fields.


363-374: Effective session deactivation implementation.

The deactivateAllSessions method correctly matches the user and their active token relationships, then deactivates them by setting active: false. This aligns with the Cypher database pattern and supports the requirement to log out disabled users.

@CarsonF CarsonF force-pushed the disabled-user-no-login branch from cd16a3a to 930dba2 Compare June 20, 2025 16:09
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