Buckets:
AnonymousSpottedToad/candidate_bucket / codebase /python /mdfarhankc_fastapi-fullauth /fastapi_fullauth /protection /lockout.py
| import logging | |
| import time | |
| from abc import ABC, abstractmethod | |
| from typing import TYPE_CHECKING, Any | |
| if TYPE_CHECKING: | |
| from fastapi_fullauth.config import FullAuthConfig | |
| logger = logging.getLogger("fastapi_fullauth.lockout") | |
| class LockoutManager(ABC): | |
| """Abstract lockout manager interface.""" | |
| def __init__(self, max_attempts: int = 5, lockout_seconds: int = 900) -> None: | |
| self.max_attempts = max_attempts | |
| self.lockout_seconds = lockout_seconds | |
| async def is_locked(self, key: str) -> bool: ... | |
| async def record_failure(self, key: str) -> None: ... | |
| async def clear(self, key: str) -> None: ... | |
| async def aclose(self) -> None: # noqa: B027 | |
| """Release any held resources. No-op unless overridden.""" | |
| class InMemoryLockoutManager(LockoutManager): | |
| """In-memory lockout manager. Works for single-process deployments.""" | |
| def __init__(self, max_attempts: int = 5, lockout_seconds: int = 900) -> None: | |
| super().__init__(max_attempts, lockout_seconds) | |
| self._attempts: dict[str, list[float]] = {} | |
| self._locked_until: dict[str, float] = {} | |
| async def is_locked(self, key: str) -> bool: | |
| until = self._locked_until.get(key) | |
| if until is None: | |
| return False | |
| if time.monotonic() >= until: | |
| await self.clear(key) | |
| return False | |
| return True | |
| async def record_failure(self, key: str) -> None: | |
| now = time.monotonic() | |
| attempts = self._attempts.setdefault(key, []) | |
| cutoff = now - self.lockout_seconds | |
| attempts[:] = [t for t in attempts if t > cutoff] | |
| attempts.append(now) | |
| if len(attempts) >= self.max_attempts: | |
| self._locked_until[key] = now + self.lockout_seconds | |
| logger.warning( | |
| "Account locked after %d failed attempts: %s", | |
| self.max_attempts, | |
| key, | |
| ) | |
| async def clear(self, key: str) -> None: | |
| self._attempts.pop(key, None) | |
| self._locked_until.pop(key, None) | |
| class RedisLockoutManager(LockoutManager): | |
| """Redis-backed lockout manager. Works across multiple workers.""" | |
| def __init__( | |
| self, | |
| redis_url: str, | |
| max_attempts: int = 5, | |
| lockout_seconds: int = 900, | |
| ) -> None: | |
| super().__init__(max_attempts, lockout_seconds) | |
| from fastapi_fullauth.core._redis import acquire_redis | |
| self._redis = acquire_redis(redis_url, feature="the Redis lockout manager") | |
| self._redis_url: str | None = redis_url | |
| self._prefix = "fullauth:lockout:" | |
| async def is_locked(self, key: str) -> bool: | |
| locked = await self._redis.get(f"{self._prefix}locked:{key}") | |
| return locked is not None | |
| async def record_failure(self, key: str) -> None: | |
| attempts_key = f"{self._prefix}attempts:{key}" | |
| locked_key = f"{self._prefix}locked:{key}" | |
| pipe = self._redis.pipeline() | |
| pipe.incr(attempts_key) | |
| pipe.expire(attempts_key, self.lockout_seconds) | |
| results = await pipe.execute() | |
| count = results[0] | |
| if count >= self.max_attempts: | |
| # Set the lock and clear the counter in one round-trip so a concurrent | |
| # burst can't observe a half-applied state. | |
| lock_pipe = self._redis.pipeline() | |
| lock_pipe.setex(locked_key, self.lockout_seconds, "1") | |
| lock_pipe.delete(attempts_key) | |
| await lock_pipe.execute() | |
| logger.warning( | |
| "Account locked after %d failed attempts: %s", | |
| self.max_attempts, | |
| key, | |
| ) | |
| async def clear(self, key: str) -> None: | |
| pipe = self._redis.pipeline() | |
| pipe.delete(f"{self._prefix}attempts:{key}") | |
| pipe.delete(f"{self._prefix}locked:{key}") | |
| await pipe.execute() | |
| async def aclose(self) -> None: | |
| from fastapi_fullauth.core._redis import release_redis | |
| if self._redis_url is not None: | |
| await release_redis(self._redis_url) | |
| self._redis_url = None | |
| _lockout_registry: dict[str, type[LockoutManager]] = { | |
| "memory": InMemoryLockoutManager, | |
| "redis": RedisLockoutManager, | |
| } | |
| def register_lockout_backend(name: str, cls: type[LockoutManager]) -> None: | |
| """Register a custom lockout backend. | |
| Usage:: | |
| class DatabaseLockoutManager(LockoutManager): | |
| ... | |
| register_lockout_backend("database", DatabaseLockoutManager) | |
| # Then set LOCKOUT_BACKEND="database" in config | |
| """ | |
| _lockout_registry[name] = cls | |
| def create_lockout(config: "FullAuthConfig") -> LockoutManager | None: | |
| """Create a lockout manager based on config. Returns None if disabled.""" | |
| if not config.LOCKOUT_ENABLED: | |
| return None | |
| backend_cls = _lockout_registry.get(config.LOCKOUT_BACKEND) | |
| if backend_cls is None: | |
| raise ValueError( | |
| f"Unknown lockout backend: {config.LOCKOUT_BACKEND}. " | |
| f"Available: {', '.join(sorted(_lockout_registry))}. " | |
| f"Register custom backends with register_lockout_backend()." | |
| ) | |
| kwargs: dict[str, Any] = { | |
| "max_attempts": config.MAX_LOGIN_ATTEMPTS, | |
| "lockout_seconds": config.LOCKOUT_DURATION_MINUTES * 60, | |
| } | |
| if config.LOCKOUT_BACKEND == "redis": | |
| if not config.REDIS_URL: | |
| raise ValueError("REDIS_URL must be set when LOCKOUT_BACKEND='redis'") | |
| kwargs["redis_url"] = config.REDIS_URL | |
| return backend_cls(**kwargs) | |
Xet Storage Details
- Size:
- 5.59 kB
- Xet hash:
- aedba055a1ad48db959a875a7f8d477c3704198d6f04f87b5df209442613d7ba
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.