Skip to content

fix: enforce one active token per user - #808

Open
goelsonali wants to merge 1 commit into
Women-Coding-Community:mainfrom
goelsonali:fix/user-token-cache-ttl
Open

goelsonali wants to merge 1 commit into
Women-Coding-Community:mainfrom
goelsonali:fix/user-token-cache-ttl

Conversation

@goelsonali

Copy link
Copy Markdown
Contributor

Description

Issue :
Unconditionally inserted a new token with no cap and no revocation of prior sessions; QA reproduced this by issuing 100 logins for one account and ending up with 100 simultaneously valid tokens, bounded only by the configured TTL.

Resolution :

  1. Login now enforces exactly one active token per user: a Postgres advisory lock scoped to the transaction serializes concurrent logins for the same user ID, after which any existing active tokens are revoked before the new one is created.
  2. A Caffeine-backed cache now sits in front of the user_tokens table (CachingUserTokenRepository)
  • so the per-request token validation used by every authenticated call avoids a database round-trip.
  • every write path that changes a token's validity (create, revoke, revoke-all) updates or evicts the corresponding cache entry in the same call.

Closes #655

Related Issue

Please link to the issue here

Change Type

  • Bug Fix
  • New Feature
  • Code Refactor
  • Documentation
  • Test
  • Other

Screenshots

Pull request checklist

Please check if your PR fulfills the following requirements:

@sonarqubecloud

sonarqubecloud Bot commented Oct 5, 2026

Copy link
Copy Markdown

*/
@Primary
@Repository
public class CachingUserTokenRepository implements UserTokenRepository {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

I think you can review the PostgresMenteeRepository that show how to use Cacheable and is not needed to create another repository

@goelsonali goelsonali Oct 12, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

@dricazenck - I cannot leverage the just the @Cacheable annotation as is, because it is not suitable for the findValidByToken method due to the custom logic of checking the token's validity (isRevoked and expiresAt).
The @Cacheable annotation caches the result of a method based on its parameters, and it does not allow for dynamic validation logic like the one I have implemented for findValidByToken.

This branch has not been deployed

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

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat: Cap concurrent active login tokens per user

2 participants