forked from mtusi2026/mtusi2026lab2
Отзывать сессию в кэше до удаления в PostgreSQL
This commit is contained in:
+8
-3
@@ -7,10 +7,10 @@ import secrets
|
||||
from argon2 import PasswordHasher
|
||||
from argon2.exceptions import InvalidHashError, VerificationError
|
||||
|
||||
from cache import cache
|
||||
from cache import REVOKED, CacheUnavailable, cache
|
||||
from config import settings
|
||||
from db import iso
|
||||
from errors import BASIC_CHALLENGE, BEARER_CHALLENGE, unauthorized
|
||||
from errors import BASIC_CHALLENGE, BEARER_CHALLENGE, ApiError, unauthorized
|
||||
import store
|
||||
|
||||
USERNAME = re.compile(r'^[a-z0-9_]{3,32}$')
|
||||
@@ -78,6 +78,8 @@ def authenticate(header):
|
||||
raise unauthorized(BEARER_CHALLENGE)
|
||||
digest = token_hash(token)
|
||||
user = cache.get(digest)
|
||||
if user == REVOKED:
|
||||
raise unauthorized(BEARER_CHALLENGE)
|
||||
if user is None:
|
||||
row = store.session_user(digest)
|
||||
if row is None:
|
||||
@@ -88,5 +90,8 @@ def authenticate(header):
|
||||
|
||||
|
||||
def logout(session):
|
||||
try:
|
||||
cache.revoke(session['token_hash'])
|
||||
except CacheUnavailable:
|
||||
raise ApiError(503, 'Отзыв сессии временно недоступен') from None
|
||||
store.delete_session(session['token_hash'])
|
||||
cache.delete(session['token_hash'])
|
||||
|
||||
+16
-10
@@ -10,6 +10,11 @@ from config import settings
|
||||
log = logging.getLogger('messenger.cache')
|
||||
|
||||
BYPASS_SECONDS = 5
|
||||
REVOKED = 'revoked'
|
||||
|
||||
|
||||
class CacheUnavailable(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class SessionCache:
|
||||
@@ -19,14 +24,18 @@ class SessionCache:
|
||||
self.max_ttl = max_ttl
|
||||
self.bypass_until = 0.0
|
||||
|
||||
def _run(self, action):
|
||||
if self.client is None or time.monotonic() < self.bypass_until:
|
||||
def _run(self, action, required=False):
|
||||
if self.client is None:
|
||||
return None
|
||||
if not required and time.monotonic() < self.bypass_until:
|
||||
return None
|
||||
try:
|
||||
return action(self.client)
|
||||
except redis.RedisError as error:
|
||||
log.warning('session cache unavailable (%s), using PostgreSQL for %ds', type(error).__name__, BYPASS_SECONDS)
|
||||
self.bypass_until = time.monotonic() + BYPASS_SECONDS
|
||||
if required:
|
||||
raise CacheUnavailable from None
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
@@ -35,8 +44,8 @@ class SessionCache:
|
||||
|
||||
def get(self, token_hash):
|
||||
raw = self._run(lambda c: c.get(self.key(token_hash)))
|
||||
if not raw:
|
||||
return None
|
||||
if not raw or raw == REVOKED:
|
||||
return raw or None
|
||||
entry = json.loads(raw)
|
||||
if entry['expires_at'] <= time.time():
|
||||
return None
|
||||
@@ -48,13 +57,10 @@ class SessionCache:
|
||||
if ttl <= 0:
|
||||
return
|
||||
value = json.dumps({'user': user, 'expires_at': expires_at.timestamp()}, ensure_ascii=False)
|
||||
self._run(lambda c: c.set(self.key(token_hash), value, ex=ttl))
|
||||
self._run(lambda c: c.set(self.key(token_hash), value, ex=ttl, nx=True))
|
||||
|
||||
def delete(self, token_hash):
|
||||
self._run(lambda c: c.delete(self.key(token_hash)))
|
||||
|
||||
def ping(self):
|
||||
return bool(self._run(lambda c: c.ping()))
|
||||
def revoke(self, token_hash):
|
||||
self._run(lambda c: c.set(self.key(token_hash), REVOKED, ex=self.max_ttl), required=True)
|
||||
|
||||
|
||||
cache = SessionCache(settings.cache_url, settings.session_cache_ttl)
|
||||
|
||||
Reference in New Issue
Block a user