22from flask import request , jsonify , session , Blueprint
33import jwt
44from config .auth_config import AuthMethod , AuthConfig
5- from services .auth_service import blacklisted_tokens
5+ from services .auth_service import blacklisted_tokens , invalidated_sessions
66
77class AuthMiddleware :
8- def __init__ (self , auth_config : AuthConfig ):
9- self .auth_config = auth_config
8+ def __init__ (self , config : AuthConfig ):
9+ self .config = config
1010
11- def protect_blueprint (self , blueprint : Blueprint ):
11+ def protect_blueprint (self , blueprint ):
12+ """Add authentication middleware to all routes in a blueprint"""
1213 @blueprint .before_request
13- def verify_request ():
14- if self .auth_config .auth_method == AuthMethod .NONE :
14+ @wraps (blueprint )
15+ def authenticate ():
16+ if self .config .auth_method == AuthMethod .NONE :
1517 return None
1618
17- auth_handlers = {
18- AuthMethod .API_KEY : self ._handle_api_key ,
19- AuthMethod .JWT : self ._handle_jwt ,
20- AuthMethod .SESSION : self ._handle_session
21- }
19+ if self .config .auth_method == AuthMethod .API_KEY :
20+ return self ._validate_api_key ()
21+ elif self .config .auth_method == AuthMethod .JWT :
22+ return self ._validate_jwt ()
23+ elif self .config .auth_method == AuthMethod .SESSION :
24+ return self ._validate_session ()
2225
23- handler = auth_handlers .get (self .auth_config .auth_method )
24- if not handler :
25- return jsonify ({"error" : "Invalid authentication method" }), 500
26-
27- result = handler ()
28- if result is not True :
29- return result
30-
31- return None
32-
33- def _handle_api_key (self ):
26+ def _validate_api_key (self ):
27+ """Validate API key from request header"""
3428 api_key = request .headers .get ('X-API-Key' )
3529 if not api_key :
3630 return jsonify ({"error" : "API key is required" }), 401
37- if api_key != self .auth_config .api_key :
31+ if api_key != self .config .api_key :
3832 return jsonify ({"error" : "Invalid API key" }), 401
39- return True
33+ return None
4034
41- def _handle_jwt (self ):
35+ def _validate_jwt (self ):
36+ """Validate JWT from Authorization header"""
4237 auth_header = request .headers .get ('Authorization' )
4338 if not auth_header or not auth_header .startswith ('Bearer ' ):
4439 return jsonify ({"error" : "JWT token is required" }), 401
45-
40+
4641 token = auth_header .split (' ' )[1 ]
4742 if token in blacklisted_tokens :
4843 return jsonify ({"error" : "You have been logged out. Please log in again." }), 401
49-
44+
5045 try :
51- jwt .decode (
52- token ,
53- self .auth_config .jwt_secret ,
54- algorithms = ["HS256" ],
55- options = {"verify_exp" : True }
56- )
57- return True
46+ jwt .decode (token , self .config .jwt_secret , algorithms = ["HS256" ])
47+ return None
5848 except jwt .ExpiredSignatureError :
5949 return jsonify ({"error" : "Token has expired" }), 401
6050 except jwt .InvalidTokenError as e :
6151 return jsonify ({"error" : f"Invalid JWT token: { str (e )} " }), 401
6252
63- def _handle_session (self ):
64- if not session .get ('authenticated' ):
53+ def _validate_session (self ):
54+ """Validate session authentication"""
55+ if not session .get ("authenticated" ):
6556 return jsonify ({"error" : "Valid session required" }), 401
66- return True
57+
58+ # Check if session has been invalidated
59+ current_session = request .cookies .get ('session' )
60+ if current_session and current_session in invalidated_sessions :
61+ session .clear ()
62+ return jsonify ({"error" : "Session has been invalidated" }), 401
63+
64+ return None
0 commit comments