IPBanManager¶
The IPBanManager
class handles temporary IP bans in your FastAPI application.
Overview¶
The IPBanManager
uses an in-memory cache to track banned IPs and their ban durations.
Methods¶
ban_ip¶
Ban an IP address for a specified duration.
Parameters:
- ip
: The IP address to ban
- duration
: Ban duration in seconds
Example:
is_ip_banned¶
Check if an IP address is currently banned.
Parameters:
- ip
: The IP address to check
Returns:
- bool
: True if the IP is banned, False otherwise
Example:
reset¶
Reset all banned IPs.
Example:
Usage with SecurityMiddleware¶
The IPBanManager
is automatically integrated when you use the SecurityMiddleware
:
from fastapi import FastAPI
from guard.middleware import SecurityMiddleware
from guard.models import SecurityConfig
app = FastAPI()
config = SecurityConfig(
auto_ban_threshold=5, # Ban after 5 suspicious requests
auto_ban_duration=3600 # Ban for 1 hour
)
app.add_middleware(SecurityMiddleware, config=config)