Skip to content

auth

auth

Admin authentication: IP whitelist + bcrypt password + HMAC session cookie.

AdminAuthMiddleware

Bases: BaseHTTPMiddleware

IP whitelist + session-based authentication for admin routes.

dispatch(request, call_next) async

Check IP whitelist, then session, redirect to login if needed.

Source code in pspcz_analyzer/admin/auth.py
async def dispatch(self, request: Request, call_next: Any) -> Response:
    """Check IP whitelist, then session, redirect to login if needed."""
    path = request.url.path

    # Allow login page and static assets without auth
    if path in ("/admin/login", "/admin/static"):
        return await self._check_ip_then_proceed(request, call_next)

    return await self._check_ip_then_proceed(request, call_next, require_session=True)

verify_password(password)

Verify password against stored bcrypt hash.

Source code in pspcz_analyzer/admin/auth.py
def verify_password(password: str) -> bool:
    """Verify password against stored bcrypt hash."""
    if not ADMIN_PASSWORD_HASH:
        return False
    try:
        return bcrypt.checkpw(password.encode("utf-8"), ADMIN_PASSWORD_HASH.encode("utf-8"))
    except Exception:
        logger.opt(exception=True).warning("[admin-auth] bcrypt verification error")
        return False

Create a new signed session cookie value.

Source code in pspcz_analyzer/admin/auth.py
def create_session_cookie(username: str) -> str:
    """Create a new signed session cookie value."""
    expires = int(time.time()) + _SESSION_TTL
    return _sign_session(username, expires)

get_session_username(request)

Extract and verify the admin session from request cookies.

Source code in pspcz_analyzer/admin/auth.py
def get_session_username(request: Request) -> str | None:
    """Extract and verify the admin session from request cookies."""
    token = request.cookies.get(_SESSION_COOKIE)
    if not token:
        return None
    return _verify_session(token)

hash_password(password)

Generate bcrypt hash for a password. Used by CLI helper.

Source code in pspcz_analyzer/admin/auth.py
def hash_password(password: str) -> str:
    """Generate bcrypt hash for a password. Used by CLI helper."""
    return bcrypt.hashpw(password.encode("utf-8"), bcrypt.gensalt()).decode("utf-8")