|
|
from functools import wraps |
|
|
from flask import redirect, url_for, flash, jsonify |
|
|
from flask_login import current_user |
|
|
|
|
|
def admin_required(f): |
|
|
"""Decorator to restrict access to admin users only.""" |
|
|
@wraps(f) |
|
|
def decorated_function(*args, **kwargs): |
|
|
if not current_user.is_authenticated or current_user.role != "admin": |
|
|
flash("You do not have permission to access this page.", "error") |
|
|
return redirect(url_for("dashboard.index")) |
|
|
return f(*args, **kwargs) |
|
|
return decorated_function |
|
|
|
|
|
def login_required_json(f): |
|
|
"""Decorator to require login for JSON API endpoints.""" |
|
|
@wraps(f) |
|
|
def decorated_function(*args, **kwargs): |
|
|
if not current_user.is_authenticated: |
|
|
return jsonify({"error": "Login required"}), 401 |
|
|
return f(*args, **kwargs) |
|
|
return decorated_function |
|
|
|
|
|
def cache_response(timeout=60): |
|
|
def decorator(f): |
|
|
@wraps(f) |
|
|
def decorated_function(*args, **kwargs): |
|
|
from flask import request |
|
|
from .. import cache |
|
|
|
|
|
cache_key = f"{request.path}:{request.query_string}" |
|
|
cached_response = cache.get(cache_key) |
|
|
if cached_response: |
|
|
return cached_response |
|
|
response = f(*args, **kwargs) |
|
|
cache.set(cache_key, response, timeout=timeout) |
|
|
return response |
|
|
return decorated_function |
|
|
return decorator |