forked from mtusi2026/mtusi2026lab3
4_grade
This commit is contained in:
+170
@@ -0,0 +1,170 @@
|
||||
|
||||
import secrets
|
||||
import datetime
|
||||
from uuid import UUID
|
||||
|
||||
from argon2 import PasswordHasher
|
||||
from argon2.exceptions import VerifyMismatchError
|
||||
from fastapi import Header, HTTPException, status
|
||||
|
||||
from src import config, database
|
||||
|
||||
|
||||
ph = PasswordHasher()
|
||||
|
||||
|
||||
def _get_pool():
|
||||
"""Возвращает актуальный пул подключений PostgreSQL."""
|
||||
if database.pool is None:
|
||||
raise RuntimeError("Database connection pool is not initialized")
|
||||
return database.pool
|
||||
|
||||
|
||||
def hash_password(password: str) -> str:
|
||||
return ph.hash(password)
|
||||
|
||||
|
||||
def verify_password(password_hash: str, password: str) -> bool:
|
||||
try:
|
||||
return ph.verify(password_hash, password)
|
||||
except VerifyMismatchError:
|
||||
return False
|
||||
|
||||
|
||||
def generate_token() -> str:
|
||||
return secrets.token_hex(32)
|
||||
|
||||
|
||||
async def create_session(user_id: UUID) -> dict:
|
||||
token = generate_token()
|
||||
|
||||
expires_at = (
|
||||
datetime.datetime.now(datetime.timezone.utc)
|
||||
+ datetime.timedelta(seconds=config.SESSION_TTL_SECONDS)
|
||||
)
|
||||
|
||||
pool = _get_pool()
|
||||
|
||||
async with pool.acquire() as conn:
|
||||
await conn.execute(
|
||||
"""
|
||||
INSERT INTO sessions (token, user_id, expires_at)
|
||||
VALUES ($1, $2, $3)
|
||||
""",
|
||||
token,
|
||||
user_id,
|
||||
expires_at,
|
||||
)
|
||||
|
||||
return {
|
||||
"token": token,
|
||||
"expires_at": expires_at,
|
||||
}
|
||||
|
||||
|
||||
async def get_session(token: str) -> dict | None:
|
||||
pool = _get_pool()
|
||||
|
||||
async with pool.acquire() as conn:
|
||||
row = await conn.fetchrow(
|
||||
"""
|
||||
SELECT token, user_id, expires_at
|
||||
FROM sessions
|
||||
WHERE token = $1
|
||||
AND expires_at > NOW()
|
||||
""",
|
||||
token,
|
||||
)
|
||||
|
||||
if row is None:
|
||||
return None
|
||||
|
||||
return {
|
||||
"token": row["token"],
|
||||
"user_id": row["user_id"],
|
||||
"expires_at": row["expires_at"],
|
||||
}
|
||||
|
||||
|
||||
async def revoke_session(token: str):
|
||||
pool = _get_pool()
|
||||
|
||||
async with pool.acquire() as conn:
|
||||
await conn.execute(
|
||||
"DELETE FROM sessions WHERE token = $1",
|
||||
token,
|
||||
)
|
||||
|
||||
|
||||
async def get_current_user(
|
||||
authorization: str = Header(default="")
|
||||
):
|
||||
if not authorization.startswith("Bearer "):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail={
|
||||
"error": {
|
||||
"code": "unauthorized",
|
||||
"message": "invalid auth scheme",
|
||||
"request_id": "",
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
token = authorization.split(" ", 1)[1].strip()
|
||||
|
||||
if not token:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail={
|
||||
"error": {
|
||||
"code": "unauthorized",
|
||||
"message": "missing token",
|
||||
"request_id": "",
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
session = await get_session(token)
|
||||
|
||||
if session is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail={
|
||||
"error": {
|
||||
"code": "unauthorized",
|
||||
"message": "invalid or expired token",
|
||||
"request_id": "",
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
pool = _get_pool()
|
||||
|
||||
async with pool.acquire() as conn:
|
||||
user = await conn.fetchrow(
|
||||
"""
|
||||
SELECT id, username, display_name, created_at
|
||||
FROM users
|
||||
WHERE id = $1
|
||||
""",
|
||||
session["user_id"],
|
||||
)
|
||||
|
||||
if user is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail={
|
||||
"error": {
|
||||
"code": "unauthorized",
|
||||
"message": "user not found",
|
||||
"request_id": "",
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
return {
|
||||
"user_id": user["id"],
|
||||
"user": user,
|
||||
"token": token,
|
||||
}
|
||||
Reference in New Issue
Block a user