feat: add refresh_user_cache method and integrate cache refresh in auth flows

Add a new `refresh_user_cache` method to `DataAccessLayer` that re-caches user objects by both ID and username with the configured TTL. Update `basic_auth` and `webdav_auth` handlers to call this method after successful authentication, ensuring the enterprise cache stays synchronized with user lookups from the fallback ORM path.
This commit is contained in:
retoor 2025-11-29 11:27:08 +00:00
parent 2d26306352
commit 049e477ee9
2 changed files with 22 additions and 7 deletions

View File

@ -148,6 +148,10 @@ class DataAccessLayer:
await self._cache.delete(self._user_by_name_key(username))
await self._cache.invalidate_prefix(f"u:{user_id}:")
async def refresh_user_cache(self, user):
await self._cache.set(self._user_key(user.id), user, ttl=self.TTL_USER)
await self._cache.set(self._user_by_name_key(user.username), user, ttl=self.TTL_USER)
async def get_folder(
self,
user_id: int,

View File

@ -75,14 +75,24 @@ async def basic_auth(authorization: Optional[str] = Header(None)):
decoded = base64.b64decode(credentials).decode("utf-8")
username, password = decoded.split(":", 1)
user = None
try:
from .enterprise.dal import get_dal
dal = get_dal()
user = await dal.get_user_by_username(username)
if user and verify_password(password, user.hashed_password):
return user
except RuntimeError:
user = await User.get_or_none(username=username)
pass
user = await User.get_or_none(username=username)
if user and verify_password(password, user.hashed_password):
try:
from .enterprise.dal import get_dal
dal = get_dal()
await dal.refresh_user_cache(user)
except RuntimeError:
pass
return user
except (ValueError, UnicodeDecodeError, base64.binascii.Error):
return None
@ -103,13 +113,14 @@ async def webdav_auth(request: Request, authorization: Optional[str] = Header(No
)
username: str = payload.get("sub")
if username:
try:
from .enterprise.dal import get_dal
dal = get_dal()
user = await dal.get_user_by_username(username)
except RuntimeError:
user = await User.get_or_none(username=username)
user = await User.get_or_none(username=username)
if user:
try:
from .enterprise.dal import get_dal
dal = get_dal()
await dal.refresh_user_cache(user)
except RuntimeError:
pass
return user
except JWTError:
pass