This implementation adds a one-time token system for the search API to help prevent DoS (Denial of Service) attacks. Users must obtain a valid token before performing a search, and each token can only be used once.
- One-time tokens: Each search token can only be used once
- Time-limited: Tokens expire after 5 minutes
- Automatic cleanup: Old tokens are automatically cleaned up (older than 1 hour)
- Transparent to users: The frontend automatically fetches and uses tokens
- Stores one-time search tokens
- Fields: token, created_at, used, ip_address
- Methods:
generate(): Creates a new search tokenvalidate_and_use(): Validates and marks a token as usedcleanup_old_tokens(): Removes tokens older than 1 hour
GET /api/search/token: Returns a new one-time search token- No authentication required
- Includes automatic periodic cleanup of old tokens
/search/: Now requires a valid token parameter/search-reviews/: Now requires a valid token parameter- Returns 403 error if token is invalid or missing
- Intercepts search form submission
- Automatically fetches a token before performing search
- Includes token in the search URL
- Pagination links automatically fetch new tokens
- Ensures seamless navigation through search results
Run the SQL migration script to create the search_tokens table:
mysql -u your_username -p your_database < migrations_search_token.sqlOr using Flask-Migrate (if configured):
flask db migrate -m "Add search_tokens table"
flask db upgradeDeploy the updated code to your server.
Test the search functionality to ensure tokens are being generated and validated correctly.
No additional configuration is required. The system uses the following defaults:
- Token expiration: 5 minutes
- Token cleanup: Tokens older than 1 hour are removed
- Token length: 32 bytes (urlsafe base64 encoded)
- Rate Limiting: Consider adding rate limiting to the
/api/search/tokenendpoint to prevent token generation abuse - IP Tracking: The system tracks IP addresses to help identify potential abuse patterns
- Monitoring: Monitor the search_tokens table size to ensure cleanup is working properly
- Check that the
search_tokenstable exists - Verify that the
/api/search/tokenendpoint is accessible - Check browser console for JavaScript errors
- Verify that the cleanup function is running
- Manually run:
DELETE FROM search_tokens WHERE created_at < DATE_SUB(NOW(), INTERVAL 1 HOUR);
- Tokens may be expiring too quickly if there's clock skew
- Users may have JavaScript disabled (tokens require JavaScript)
- Check that tokens are being generated correctly
Consider implementing:
- Rate limiting on token generation per IP
- CAPTCHA for suspicious IPs
- Metrics/monitoring for token usage
- Admin dashboard to monitor search API usage