added a session storage policy in Redis
This commit is contained in:
+10
-38
@@ -1,3 +1,4 @@
|
||||
from redis.asyncio import Redis
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.schemas.session import AuthSession
|
||||
@@ -6,49 +7,20 @@ from app.schemas.user import User
|
||||
|
||||
async def create_session(
|
||||
session: AsyncSession,
|
||||
redis: Redis,
|
||||
username: str,
|
||||
password: str,
|
||||
ttl_seconds: int,
|
||||
) -> AuthSession:
|
||||
"""POST /auth/sessions (username/password уже извлечены из Basic в endpoints).
|
||||
|
||||
Алгоритм:
|
||||
1. user = await storage.users.get_user_by_username(session, username)
|
||||
2. если user is None:
|
||||
await security.dummy_verify_password(password)
|
||||
raise unauthorized_basic()
|
||||
3. если not await security.verify_password(password, user.password_hash):
|
||||
raise unauthorized_basic() (тот же ответ, что и в п.2)
|
||||
4. token = security.generate_token(); token_hash = security.hash_token(token)
|
||||
5. expires_at = datetime.now(UTC) + timedelta(seconds=ttl_seconds)
|
||||
6. await storage.sessions.create_session(session, user_id=user.id, token_hash=..., expires_at=...)
|
||||
await session.commit()
|
||||
7. return AuthSession(token=token, expires_at=expires_at, user=to_user_schema(user))
|
||||
(токен показывается клиенту ровно один раз)
|
||||
"""
|
||||
raise NotImplementedError("TODO")
|
||||
"""Проверяет учётные данные и выдаёт новый Bearer-токен."""
|
||||
raise NotImplementedError
|
||||
|
||||
|
||||
async def authenticate_token(session: AsyncSession, token: str) -> User:
|
||||
"""Bearer-токен -> текущий пользователь (dependency на всех бизнес-endpoint).
|
||||
|
||||
Алгоритм:
|
||||
1. user = await storage.sessions.get_user_by_active_token_hash(
|
||||
session, security.hash_token(token), datetime.now(UTC))
|
||||
2. user is None (неизвестен/истёк/отозван) -> raise unauthorized_bearer()
|
||||
3. return to_user_schema(user)
|
||||
Это AUTHENTICATION («кто ты»). «Можно ли тебе в этот чат» (AUTHORIZATION) —
|
||||
отдельная проверка членства в domain.chats; посторонний получает 404, не 403.
|
||||
"""
|
||||
raise NotImplementedError("TODO")
|
||||
async def authenticate_token(session: AsyncSession, redis: Redis, token: str) -> User:
|
||||
"""Возвращает владельца действующей сессии или бросает 401."""
|
||||
raise NotImplementedError
|
||||
|
||||
|
||||
async def revoke_session(session: AsyncSession, token: str) -> None:
|
||||
"""DELETE /auth/sessions/current.
|
||||
|
||||
Алгоритм:
|
||||
1. revoked = await storage.sessions.revoke_session(session, security.hash_token(token), datetime.now(UTC))
|
||||
2. not revoked -> raise unauthorized_bearer() (повторный logout = 401)
|
||||
3. await session.commit()
|
||||
"""
|
||||
raise NotImplementedError("TODO")
|
||||
async def revoke_session(redis: Redis, token: str) -> None:
|
||||
"""Отзывает текущую сессию; повторный отзыв даёт 401."""
|
||||
raise NotImplementedError
|
||||
|
||||
Reference in New Issue
Block a user