feat: enhance database queries with error handling and improve SQL statement readability

Co-authored-by: Copilot <copilot@github.com>
This commit is contained in:
2026-04-29 16:28:22 +02:00
parent df85676fa2
commit 8e36f48527
4 changed files with 70 additions and 67 deletions
+23 -28
View File
@@ -35,7 +35,8 @@ def verify_password(plain: str, hashed: str) -> bool:
# --- Tokens ---
def create_access_token(user_id: str, email: str, role: str) -> str:
expire = datetime.now(timezone.utc) + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
expire = datetime.now(timezone.utc) + \
timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
payload = {
"sub": user_id,
"email": email,
@@ -47,7 +48,8 @@ def create_access_token(user_id: str, email: str, role: str) -> str:
def create_refresh_token(user_id: str, jti: str) -> str:
expire = datetime.now(timezone.utc) + timedelta(days=REFRESH_TOKEN_EXPIRE_DAYS)
expire = datetime.now(timezone.utc) + \
timedelta(days=REFRESH_TOKEN_EXPIRE_DAYS)
payload = {
"sub": user_id,
"jti": jti,
@@ -68,28 +70,25 @@ async def register_user(email: str, password: str) -> dict[str, Any]:
"""Insert a new user. Returns the created user row."""
conn = get_conn()
lock = get_write_lock()
sql_check = "SELECT id FROM users WHERE email = ?"
sql_insert = "INSERT INTO users (email, password_hash) VALUES (?, ?)"
sql_fetch = "SELECT id, email, role FROM users WHERE email = ?"
async with lock:
existing = conn.execute(
"SELECT id FROM users WHERE email = ?", [email]
).fetchone()
existing = conn.execute(sql_check, [email]).fetchone()
if existing:
raise ValueError("Email already registered.")
conn.execute(
"INSERT INTO users (email, password_hash) VALUES (?, ?)",
[email, hash_password(password)],
)
row = conn.execute(
"SELECT id, email, role FROM users WHERE email = ?", [email]
).fetchone()
conn.execute(sql_insert, [email, hash_password(password)],)
row = conn.execute(sql_fetch, [email]).fetchone()
if row is None:
raise RuntimeError("Failed to fetch user after registration.")
return {"id": str(row[0]), "email": row[1], "role": row[2]}
async def authenticate_user(email: str, password: str) -> dict[str, Any] | None:
"""Return user dict if credentials are valid, else None."""
conn = get_conn()
row = conn.execute(
"SELECT id, email, password_hash, role FROM users WHERE email = ?", [email]
).fetchone()
sql_fetch = "SELECT id, email, password_hash, role FROM users WHERE email = ?"
row = conn.execute(sql_fetch, [email]).fetchone()
if row is None or not verify_password(password, row[2]):
return None
return {"id": str(row[0]), "email": row[1], "role": row[3]}
@@ -99,34 +98,30 @@ async def store_refresh_token(user_id: str, jti: str) -> None:
"""Persist a refresh token JTI in the database."""
conn = get_conn()
lock = get_write_lock()
sql_insert = "INSERT INTO refresh_tokens (jti, user_id, expires_at) VALUES (?, ?, ?)"
from datetime import timedelta
expires_at = datetime.now(timezone.utc) + timedelta(days=REFRESH_TOKEN_EXPIRE_DAYS)
expires_at = datetime.now(timezone.utc) + \
timedelta(days=REFRESH_TOKEN_EXPIRE_DAYS)
async with lock:
conn.execute(
"INSERT INTO refresh_tokens (jti, user_id, expires_at) VALUES (?, ?, ?)",
[jti, user_id, expires_at],
)
conn.execute(sql_insert, [jti, user_id, expires_at])
async def revoke_refresh_token(jti: str) -> None:
"""Mark a refresh token as revoked."""
conn = get_conn()
lock = get_write_lock()
sql_update = "UPDATE refresh_tokens SET revoked = true WHERE jti = ?"
async with lock:
conn.execute(
"UPDATE refresh_tokens SET revoked = true WHERE jti = ?", [jti]
)
conn.execute(sql_update, [jti])
async def validate_refresh_token_jti(jti: str, user_id: str) -> bool:
"""Return True if the JTI exists, is not revoked, and belongs to user_id."""
conn = get_conn()
now = datetime.now(timezone.utc)
row = conn.execute(
"""
sql_select = """
SELECT 1 FROM refresh_tokens
WHERE jti = ? AND user_id = ? AND revoked = false AND expires_at > ?
""",
[jti, user_id, now],
).fetchone()
"""
row = conn.execute(sql_select, [jti, user_id, now]).fetchone()
return row is not None