Add initial shared code packages
This commit is contained in:
commit
838a97d344
54 files changed
+6265
No files matched your search
@@ -0,0 +1,18 @@
|
||||
"""Shared PostgreSQL and authentication primitives for Python services."""
|
||||
|
||||
from .auth import AuthStore, AuthUser, hash_password, verify_password
|
||||
from .config import DatabaseConfig, database_url_from_env
|
||||
from .postgres import Database
|
||||
from .tokens import hash_token, new_session_token
|
||||
|
||||
__all__ = [
|
||||
"AuthStore",
|
||||
"AuthUser",
|
||||
"Database",
|
||||
"DatabaseConfig",
|
||||
"database_url_from_env",
|
||||
"hash_password",
|
||||
"hash_token",
|
||||
"new_session_token",
|
||||
"verify_password",
|
||||
]
|
||||
@@ -0,0 +1,150 @@
|
||||
"""Shared account/session persistence and password helpers."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime
|
||||
|
||||
import asyncpg
|
||||
import bcrypt
|
||||
|
||||
from .postgres import Database
|
||||
|
||||
_SCHEMA = """
|
||||
CREATE TABLE IF NOT EXISTS auth_users (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
username TEXT NOT NULL UNIQUE,
|
||||
email TEXT NOT NULL DEFAULT '',
|
||||
password_hash TEXT NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS email TEXT NOT NULL DEFAULT '';
|
||||
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ NOT NULL DEFAULT now();
|
||||
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS updated_at TIMESTAMPTZ NOT NULL DEFAULT now();
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS auth_users_email_idx ON auth_users (lower(email)) WHERE email <> '';
|
||||
CREATE TABLE IF NOT EXISTS auth_sessions (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
user_id BIGINT NOT NULL REFERENCES auth_users(id) ON DELETE CASCADE,
|
||||
token_hash TEXT NOT NULL UNIQUE,
|
||||
expires_at TIMESTAMPTZ NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS auth_sessions_expiry_idx ON auth_sessions (expires_at);
|
||||
CREATE INDEX IF NOT EXISTS auth_sessions_user_idx ON auth_sessions (user_id);
|
||||
"""
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class AuthUser:
|
||||
id: int
|
||||
username: str
|
||||
email: str
|
||||
password_hash: str
|
||||
created_at: datetime | None = None
|
||||
updated_at: datetime | None = None
|
||||
|
||||
|
||||
class UserExistsError(Exception):
|
||||
"""Raised when a user violates a unique or single-user constraint."""
|
||||
|
||||
|
||||
def hash_password(password: str) -> str:
|
||||
if len(password) < 8:
|
||||
raise ValueError("Password must be at least 8 characters")
|
||||
return bcrypt.hashpw(password.encode("utf-8"), bcrypt.gensalt()).decode("utf-8")
|
||||
|
||||
|
||||
def verify_password(password: str, stored_hash: str) -> bool:
|
||||
try:
|
||||
return bcrypt.checkpw(password.encode("utf-8"), stored_hash.encode("utf-8"))
|
||||
except (ValueError, TypeError):
|
||||
return False
|
||||
|
||||
|
||||
class AuthStore:
|
||||
def __init__(self, database: Database, *, single_user: bool = True) -> None:
|
||||
self.database = database
|
||||
self.single_user = single_user
|
||||
|
||||
async def ensure_schema(self) -> None:
|
||||
await self.database.execute(_SCHEMA)
|
||||
if self.single_user:
|
||||
await self.database.execute(
|
||||
"CREATE UNIQUE INDEX IF NOT EXISTS auth_users_singleton_idx ON auth_users ((true))"
|
||||
)
|
||||
|
||||
async def count_users(self) -> int:
|
||||
return int(await self.database.fetchval("SELECT count(*) FROM auth_users"))
|
||||
|
||||
async def create_user(self, username: str, email: str, password_hash: str) -> AuthUser:
|
||||
try:
|
||||
row = await self.database.fetchrow(
|
||||
"""
|
||||
INSERT INTO auth_users (username, email, password_hash, updated_at)
|
||||
VALUES ($1, $2, $3, now())
|
||||
RETURNING id, username, email, password_hash, created_at, updated_at
|
||||
""",
|
||||
username,
|
||||
email,
|
||||
password_hash,
|
||||
)
|
||||
except asyncpg.UniqueViolationError as exc:
|
||||
raise UserExistsError from exc
|
||||
assert row is not None
|
||||
return AuthUser(**dict(row))
|
||||
|
||||
async def find_by_identifier(self, identifier: str) -> AuthUser | None:
|
||||
row = await self.database.fetchrow(
|
||||
"""
|
||||
SELECT id, username, email, password_hash, created_at, updated_at
|
||||
FROM auth_users
|
||||
WHERE username = $1 OR lower(email) = lower($1)
|
||||
""",
|
||||
identifier,
|
||||
)
|
||||
return AuthUser(**dict(row)) if row else None
|
||||
|
||||
async def update_credentials(
|
||||
self, user_id: int, username: str, email: str, password_hash: str
|
||||
) -> None:
|
||||
await self.database.execute(
|
||||
"""
|
||||
UPDATE auth_users
|
||||
SET username = $1, email = $2, password_hash = $3, updated_at = now()
|
||||
WHERE id = $4
|
||||
""",
|
||||
username,
|
||||
email,
|
||||
password_hash,
|
||||
user_id,
|
||||
)
|
||||
|
||||
async def create_session(self, user_id: int, token_hash: str, expires_at: datetime) -> None:
|
||||
await self.database.execute(
|
||||
"INSERT INTO auth_sessions (user_id, token_hash, expires_at) VALUES ($1, $2, $3)",
|
||||
user_id,
|
||||
token_hash,
|
||||
expires_at,
|
||||
)
|
||||
|
||||
async def find_session_user(self, token_hash: str) -> AuthUser | None:
|
||||
row = await self.database.fetchrow(
|
||||
"""
|
||||
SELECT u.id, u.username, u.email, u.password_hash, u.created_at, u.updated_at
|
||||
FROM auth_sessions s
|
||||
JOIN auth_users u ON u.id = s.user_id
|
||||
WHERE s.token_hash = $1 AND s.expires_at > now()
|
||||
""",
|
||||
token_hash,
|
||||
)
|
||||
return AuthUser(**dict(row)) if row else None
|
||||
|
||||
async def delete_session(self, token_hash: str) -> None:
|
||||
await self.database.execute("DELETE FROM auth_sessions WHERE token_hash = $1", token_hash)
|
||||
|
||||
async def delete_sessions_for_user(self, user_id: int) -> None:
|
||||
await self.database.execute("DELETE FROM auth_sessions WHERE user_id = $1", user_id)
|
||||
|
||||
async def prune_expired_sessions(self) -> None:
|
||||
await self.database.execute("DELETE FROM auth_sessions WHERE expires_at < now()")
|
||||
@@ -0,0 +1,49 @@
|
||||
"""Dependency-free environment configuration helpers."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from dataclasses import dataclass
|
||||
from typing import Mapping
|
||||
|
||||
|
||||
def _int_value(env: Mapping[str, str], key: str, fallback: int, minimum: int) -> int:
|
||||
try:
|
||||
value = int(env.get(key, ""))
|
||||
except (TypeError, ValueError):
|
||||
return fallback
|
||||
return value if value >= minimum else fallback
|
||||
|
||||
|
||||
def database_url_from_env(env: Mapping[str, str] | None = None) -> str:
|
||||
source = os.environ if env is None else env
|
||||
value = str(source.get("DATABASE_URL", "")).strip()
|
||||
if not value:
|
||||
raise RuntimeError("DATABASE_URL environment variable is required")
|
||||
return value
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class DatabaseConfig:
|
||||
dsn: str
|
||||
min_size: int = 0
|
||||
max_size: int = 20
|
||||
timeout: float = 5.0
|
||||
command_timeout: float = 15.0
|
||||
|
||||
@classmethod
|
||||
def from_env(cls, env: Mapping[str, str] | None = None) -> "DatabaseConfig":
|
||||
source = os.environ if env is None else env
|
||||
max_size = _int_value(source, "DATABASE_MAX_CONNS", 20, 1)
|
||||
min_size = _int_value(source, "DATABASE_MIN_CONNS", 0, 0)
|
||||
if min_size > max_size:
|
||||
raise ValueError("DATABASE_MIN_CONNS must not exceed DATABASE_MAX_CONNS")
|
||||
return cls(
|
||||
dsn=database_url_from_env(source),
|
||||
min_size=min_size,
|
||||
max_size=max_size,
|
||||
timeout=float(_int_value(source, "DATABASE_CONNECT_TIMEOUT_SECONDS", 5, 1)),
|
||||
command_timeout=float(
|
||||
_int_value(source, "DATABASE_COMMAND_TIMEOUT_SECONDS", 15, 1)
|
||||
),
|
||||
)
|
||||
@@ -0,0 +1,65 @@
|
||||
"""Shared asyncpg pool and transaction wrapper."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from contextlib import asynccontextmanager
|
||||
from typing import Any, AsyncIterator, Awaitable, Callable, Sequence
|
||||
|
||||
import asyncpg
|
||||
|
||||
from .config import DatabaseConfig
|
||||
|
||||
|
||||
class Database:
|
||||
"""Own one asyncpg pool and expose common lifecycle/query operations."""
|
||||
|
||||
def __init__(self, pool: asyncpg.Pool) -> None:
|
||||
self.pool = pool
|
||||
|
||||
@classmethod
|
||||
async def connect(cls, config: DatabaseConfig | str) -> "Database":
|
||||
settings = config if isinstance(config, DatabaseConfig) else DatabaseConfig(dsn=config)
|
||||
pool = await asyncpg.create_pool(
|
||||
dsn=settings.dsn,
|
||||
min_size=settings.min_size,
|
||||
max_size=settings.max_size,
|
||||
timeout=settings.timeout,
|
||||
command_timeout=settings.command_timeout,
|
||||
)
|
||||
try:
|
||||
await pool.fetchval("SELECT 1")
|
||||
except Exception:
|
||||
await pool.close()
|
||||
raise
|
||||
return cls(pool)
|
||||
|
||||
async def ping(self) -> None:
|
||||
await self.pool.fetchval("SELECT 1")
|
||||
|
||||
async def close(self) -> None:
|
||||
await self.pool.close()
|
||||
|
||||
async def execute(self, query: str, *args: Any) -> str:
|
||||
return await self.pool.execute(query, *args)
|
||||
|
||||
async def fetch(self, query: str, *args: Any) -> list[asyncpg.Record]:
|
||||
return await self.pool.fetch(query, *args)
|
||||
|
||||
async def fetchrow(self, query: str, *args: Any) -> asyncpg.Record | None:
|
||||
return await self.pool.fetchrow(query, *args)
|
||||
|
||||
async def fetchval(self, query: str, *args: Any) -> Any:
|
||||
return await self.pool.fetchval(query, *args)
|
||||
|
||||
@asynccontextmanager
|
||||
async def transaction(self) -> AsyncIterator[asyncpg.Connection]:
|
||||
async with self.pool.acquire() as connection:
|
||||
async with connection.transaction():
|
||||
yield connection
|
||||
|
||||
async def with_transaction(
|
||||
self,
|
||||
callback: Callable[[asyncpg.Connection], Awaitable[Any]],
|
||||
) -> Any:
|
||||
async with self.transaction() as connection:
|
||||
return await callback(connection)
|
||||
@@ -0,0 +1,15 @@
|
||||
"""Opaque session-token generation and storage hashing."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import secrets
|
||||
|
||||
|
||||
def new_session_token() -> tuple[str, str]:
|
||||
token = secrets.token_urlsafe(32)
|
||||
return token, hash_token(token)
|
||||
|
||||
|
||||
def hash_token(token: str) -> str:
|
||||
return hashlib.sha256(token.encode("utf-8")).hexdigest()
|
||||
Reference in new issue
Block a user