Repository navigation
fix(auth): make token refresh and session restore work #210
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
Changes from 5 commits
a6c72aa
fb6e515
017e0a7
fb1f1e6
a702f7a
4377420
6a5aaf7
02992c5
5ca63bb
ae0af59
9b27aca
173404f
2aad580
1394732
de4effe
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change | ||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| @@ -1,8 +1,12 @@ | ||||||||||||||
| from .token_manager import TokenManager | ||||||||||||||
| import logging | ||||||||||||||
| import threading | ||||||||||||||
| import time | ||||||||||||||
| from typing import Dict, Any, Optional | ||||||||||||||
| from kinde_sdk.core.storage.storage_manager import StorageManager | ||||||||||||||
| from kinde_sdk.core.exceptions import KindeTokenPersistenceException | ||||||||||||||
|
|
||||||||||||||
| logger = logging.getLogger(__name__) | ||||||||||||||
|
|
||||||||||||||
| class UserSession: | ||||||||||||||
| def __init__(self): | ||||||||||||||
|
|
@@ -25,7 +29,8 @@ def set_user_data(self, user_id: str, user_info: Dict[str, Any], token_data: Dic | |||||||||||||
| # Set redirect URI if available | ||||||||||||||
| if "redirect_uri" in user_info: | ||||||||||||||
| token_manager.set_redirect_uri(user_info["redirect_uri"]) | ||||||||||||||
|
|
||||||||||||||
| self._bind_token_storage(user_id, token_manager) | ||||||||||||||
|
|
||||||||||||||
| self.user_sessions[user_id] = { | ||||||||||||||
| "user_info": user_info, | ||||||||||||||
| "token_manager": token_manager | ||||||||||||||
|
|
@@ -54,6 +59,13 @@ def _save_to_storage(self, user_id: str): | |||||||||||||
| # if you want device-specific sessions, remove the "user:" prefix | ||||||||||||||
| self.storage_manager.setItems(user_id, serialized_data) | ||||||||||||||
|
|
||||||||||||||
| def _bind_token_storage(self, user_id: str, token_manager: TokenManager): | ||||||||||||||
| """Save the session again whenever the token manager refreshes its tokens, and | ||||||||||||||
| let it read the saved tokens before refreshing, so neither a restarted process | ||||||||||||||
| nor another worker reuses a refresh token that Kinde has already rotated out.""" | ||||||||||||||
| token_manager.on_tokens_refreshed = lambda: self._save_to_storage(user_id) | ||||||||||||||
| token_manager.load_persisted_tokens = lambda: (self.storage_manager.get(user_id) or {}).get("tokens") | ||||||||||||||
|
|
||||||||||||||
| def reset(self): | ||||||||||||||
| """Reset all session data - useful for testing""" | ||||||||||||||
| with self.lock: | ||||||||||||||
|
|
@@ -94,7 +106,8 @@ def _load_from_storage(self, user_id: str) -> bool: | |||||||||||||
| # Set redirect URI if available | ||||||||||||||
| if "redirect_uri" in user_info: | ||||||||||||||
| token_manager.set_redirect_uri(user_info["redirect_uri"]) | ||||||||||||||
|
|
||||||||||||||
| self._bind_token_storage(user_id, token_manager) | ||||||||||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Register the session before binding its token-save callback.
If another instance refreshes the tokens while this load runs, the refresh calls the new callback. That callback finds no session entry, writes nothing, and returns normally. Store the session first, then bind the callback: if "redirect_uri" in user_info:
token_manager.set_redirect_uri(user_info["redirect_uri"])
- self._bind_token_storage(user_id, token_manager)
+
+ # Store in memory before binding, so a refresh save finds this session
+ self.user_sessions[user_id] = {
+ "user_info": user_info,
+ "token_manager": token_manager
+ }
+ self._bind_token_storage(user_id, token_manager)
# The token manager is shared per user, so it may already hold tokens from a refresh
# whose save failed. Those are newer than the stored copy: keep them, so the pending
# save writes them and the old, rotated refresh token is never used again
with token_manager.lock:
if not token_manager._save_pending:
token_manager.tokens = tokens
-
- # Store in memory
- self.user_sessions[user_id] = {
- "user_info": user_info,
- "token_manager": token_manager
- }
return TrueCommittable suggestion
|
||||||||||||||
|
|
||||||||||||||
| # Set tokens | ||||||||||||||
| token_manager.tokens = tokens | ||||||||||||||
|
coderabbitai[bot] marked this conversation as resolved.
Resolved
|
||||||||||||||
|
|
||||||||||||||
|
|
@@ -138,11 +151,17 @@ def is_authenticated(self, user_id: str) -> bool: | |||||||||||||
| # This will handle refreshing if needed | ||||||||||||||
| access_token = token_manager.get_access_token() | ||||||||||||||
| return access_token is not None and len(access_token) > 0 | ||||||||||||||
| except ValueError: | ||||||||||||||
| except KindeTokenPersistenceException: | ||||||||||||||
| # The refreshed tokens are valid; only saving them failed (already logged), | ||||||||||||||
| # and the save is retried on the next call | ||||||||||||||
| return True | ||||||||||||||
| except ValueError as e: | ||||||||||||||
| # Token is expired and cannot be refreshed | ||||||||||||||
| logger.info("User is not authenticated: %s", e) | ||||||||||||||
| return False | ||||||||||||||
| except Exception: | ||||||||||||||
| except Exception as e: | ||||||||||||||
| # Any other error means authentication failed | ||||||||||||||
| logger.warning("User is not authenticated: %s", type(e).__name__) | ||||||||||||||
| return False | ||||||||||||||
|
|
||||||||||||||
| def logout(self, user_id: str) -> None: | ||||||||||||||
|
|
||||||||||||||
Uh oh!
There was an error while loading. Please reload this page.