Django bot detection and email validation
Standard Django middleware plus a form validator, both fail-open so a network blip degrades to "allow" instead of a 500.
1. Install
pip install requests
2. Add the file
yourapp/middleware.py
import logging
import requests
from django.conf import settings
from django.http import JsonResponse
log = logging.getLogger(__name__)
CONURE = "https://uat.conureapi.com"
PROTECTED_PREFIXES = ("/signup", "/api/")
def client_ip(request):
forwarded = request.META.get("HTTP_X_FORWARDED_FOR", "")
if forwarded:
return forwarded.split(",")[0].strip()
return request.META.get("REMOTE_ADDR", "")
class BotCheckMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
if not request.path.startswith(PROTECTED_PREFIXES):
return self.get_response(request)
ip = client_ip(request)
if not ip:
return self.get_response(request)
try:
response = requests.post(
CONURE + "/v1/bot-check",
headers={"Authorization": "Bearer " + settings.CONURE_API_KEY},
json={"ip": ip, "user_agent": request.META.get("HTTP_USER_AGENT", "")},
timeout=3,
)
response.raise_for_status()
verdict = response.json()
except (requests.RequestException, ValueError) as error:
log.warning("conure unreachable: %s", error)
return self.get_response(request) # fail open
if verdict.get("is_bot") is True:
return JsonResponse(
{
"error": "Automated traffic is not permitted.",
"reasons": verdict.get("reasons", []),
},
status=403,
)
return self.get_response(request)3. Wire it up
# settings.py
CONURE_API_KEY = os.environ["CONURE_API_KEY"]
MIDDLEWARE = [
"django.middleware.security.SecurityMiddleware",
"yourapp.middleware.BotCheckMiddleware",
# ...
]4. Verify
Confirm the API answers before you debug your Django
wiring. The sample address sits inside a published AWS range, so a correct setup
returns is_bot: true.
curl -X POST https://uat.conureapi.com/v1/bot-check \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{"ip":"52.1.2.3","user_agent":"curl/8.4.0"}'
import requests
HEADERS = {"Authorization": "Bearer YOUR_API_KEY"}
response = requests.post(
"https://uat.conureapi.com/v1/bot-check",
headers=HEADERS,
json={"ip": "52.1.2.3", "user_agent": "curl/8.4.0"},
timeout=5,
)
response.raise_for_status()
print(response.json())
const response = await fetch("https://uat.conureapi.com/v1/bot-check", {
method: "POST",
headers: {
Authorization: "Bearer YOUR_API_KEY",
"Content-Type": "application/json",
},
body: JSON.stringify({"ip":"52.1.2.3","user_agent":"curl/8.4.0"}),
signal: AbortSignal.timeout(5000),
});
if (!response.ok) throw new Error("conure: " + response.status);
console.log(await response.json());
$curl = curl_init("https://uat.conureapi.com/v1/bot-check");
curl_setopt_array($curl, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 5,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => '{"ip":"52.1.2.3","user_agent":"curl/8.4.0"}',
CURLOPT_HTTPHEADER => [
"Authorization: Bearer YOUR_API_KEY",
"Content-Type: application/json",
],
]);
$body = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_RESPONSE_CODE);
curl_close($curl);
$verdict = $status === 200 ? json_decode($body, true) : null;
var_dump($verdict);
require "net/http"
require "json"
uri = URI("https://uat.conureapi.com/v1/bot-check")
request = Net::HTTP::Post.new(uri)
request["Authorization"] = "Bearer YOUR_API_KEY"
request["Content-Type"] = "application/json"
request.body = { ip: "52.1.2.3", user_agent: "curl/8.4.0" }.to_json
response = Net::HTTP.start(uri.hostname, uri.port,
use_ssl: uri.scheme == "https",
open_timeout: 5, read_timeout: 5) do |http|
http.request(request)
end
puts JSON.parse(response.body)
Notes
- Trusting X-Forwarded-For is only safe behind a proxy you control. Strip the header at your edge.
- Keep PROTECTED_PREFIXES tight. Every static asset that reaches the middleware is a wasted credit.