rastof9 commited on
Commit
37ebcd6
·
verified ·
1 Parent(s): 1c19e79

Create utils/decorators.py

Browse files
Files changed (1) hide show
  1. app/utils/decorators.py +35 -0
app/utils/decorators.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from functools import wraps
2
+ from flask import redirect, url_for, flash
3
+ from flask_login import current_user
4
+
5
+ def admin_required(f):
6
+ """Decorator to restrict access to admin users only."""
7
+ @wraps(f)
8
+ def decorated_function(*args, **kwargs):
9
+ if not current_user.is_authenticated or current_user.role != "admin":
10
+ flash("You do not have permission to access this page.", "error")
11
+ return redirect(url_for("dashboard.index"))
12
+ return f(*args, **kwargs)
13
+ return decorated_function
14
+
15
+ def login_required_json(f):
16
+ """Decorator to require login for JSON API endpoints."""
17
+ @wraps(f)
18
+ def decorated_function(*args, **kwargs):
19
+ if not current_user.is_authenticated:
20
+ return jsonify({"error": "Login required"}), 401
21
+ return f(*args, **kwargs)
22
+ return decorated_function
23
+
24
+ def cache_response(timeout=60):
25
+ """Decorator to cache the response of a view for a given time."""
26
+ @wraps(f)
27
+ def decorated_function(*args, **kwargs):
28
+ cache_key = request.path
29
+ cached_response = cache.get(cache_key)
30
+ if cached_response:
31
+ return cached_response
32
+ response = f(*args, **kwargs)
33
+ cache.set(cache_key, response, timeout=timeout)
34
+ return response
35
+ return decorated_function