61 lines
2.0 KiB
Python
61 lines
2.0 KiB
Python
from flask import Blueprint, jsonify, request
|
|
|
|
from api import require_auth, rate_limits, etag_response
|
|
import re
|
|
config_bp = Blueprint('config', __name__, url_prefix='/api/config')
|
|
|
|
RATE_LIMIT_REGEX = re.compile(r'^\d+\s?(per\s|/)\s?(second|minute|hour|day)$')
|
|
|
|
def is_valid_rate_limit(limit):
|
|
return bool(RATE_LIMIT_REGEX.match(limit))
|
|
@config_bp.route('/limits', methods=['GET'])
|
|
@require_auth(roles=['admin'])
|
|
@etag_response
|
|
def limits():
|
|
"""
|
|
Get all rate limits.
|
|
|
|
This endpoint retrieves a list of all rate limits configured in the system.
|
|
It requires authentication with the 'admin' role.
|
|
|
|
Returns:
|
|
A JSON object containing all rate limits, with keys in the format "endpoint : method".
|
|
|
|
Response Codes:
|
|
- 200: Success
|
|
"""
|
|
return jsonify(rate_limits), 200
|
|
|
|
@config_bp.route('/limits', methods=['PUT'])
|
|
@require_auth(roles=['admin'])
|
|
def update_limits():
|
|
"""
|
|
Update a rate limit.
|
|
|
|
This endpoint updates the rate limit for a specific endpoint and method.
|
|
It requires authentication with the 'admin' role.
|
|
|
|
Request:
|
|
- endpoint (str): The endpoint path to update
|
|
- method (str): The HTTP method to update
|
|
- new_limit (str): The new rate limit value (format: "number per second/minute/hour/day")
|
|
|
|
Returns:
|
|
A JSON object with a success message.
|
|
|
|
Response Codes:
|
|
- 200: Updated successfully
|
|
- 400: Bad request (missing required fields or invalid rate limit format)
|
|
- 404: Endpoint not found
|
|
"""
|
|
data = request.json
|
|
if not data or 'endpoint' not in data or 'method' not in data or 'new_limit' not in data:
|
|
return jsonify({'error': 'Bad request'}), 400
|
|
key = f"{data['endpoint']} : {data['method']}"
|
|
if key not in rate_limits:
|
|
return jsonify({'error': 'endpoint not found'}), 404
|
|
if is_valid_rate_limit(data['new_limit']):
|
|
rate_limits[key] = data['new_limit']
|
|
return jsonify({"message": "updated"}), 200
|
|
return jsonify({'error': 'Invalid value'}), 400
|