55from models .user import User
66from flask import session , jsonify
77
8- # Initialize auth_config as None
9- auth_config = None
10-
11- # List to store User objects
12- users = []
13-
14- # In-memory store for refresh tokens and blacklisted tokens
15- refresh_tokens = {}
16- blacklisted_tokens = set ()
8+ # --- Configuration ---
9+ auth_config = None # Global configuration object set during initialization
1710
1811def init_auth_service (config : AuthConfig ):
1912 global auth_config
2013 auth_config = config
2114
15+ # --- Storage ---
16+ users = [] # In-memory storage for user objects
17+ refresh_tokens = {} # Maps refresh tokens to usernames
18+ blacklisted_tokens = set () # Set of invalidated access tokens
19+
20+ # --- User Management ---
21+ def is_username_taken (username ):
22+ """Check if a username is already registered"""
23+ return any (user .username == username for user in users )
24+
25+ def add_user (username , password ):
26+ """Add a new user if username is not taken"""
27+ if not is_username_taken (username ):
28+ users .append (User (username , password ))
29+ return True
30+ return False
31+
32+ def validate_credentials (username , password ):
33+ """Verify username/password combination and return user if valid"""
34+ user = next ((user for user in users if user .username == username ), None )
35+ if not user or not user .check_password (password ):
36+ return None
37+ return user
38+
39+ # --- Token Management ---
2240def generate_refresh_token (username ):
41+ """Create and store a new refresh token for a user"""
2342 refresh_token = secrets .token_hex (32 )
2443 refresh_tokens [refresh_token ] = username
2544 return refresh_token
2645
2746def validate_refresh_token (refresh_token ):
47+ """Check if refresh token is valid and return associated username"""
2848 return refresh_tokens .get (refresh_token )
2949
3050def blacklist_token (token ):
51+ """Invalidate an access token"""
3152 blacklisted_tokens .add (token )
3253
3354def generate_jwt_token (username ):
55+ """Generate a new JWT access token and refresh token pair"""
3456 access_token = jwt .encode (
3557 {
3658 "sub" : username ,
3759 "iat" : datetime .datetime .utcnow (),
38- "exp" : datetime .datetime .utcnow () + datetime .timedelta (minutes = 15 ) # Shorter expiry for access token
60+ "exp" : datetime .datetime .utcnow () + datetime .timedelta (minutes = 15 )
3961 },
4062 auth_config .jwt_secret ,
4163 algorithm = "HS256"
4264 )
4365 refresh_token = generate_refresh_token (username )
4466 return access_token , refresh_token
4567
46- # Function to check if a username already exists
47- def is_username_taken (username ):
48- return any (user .username == username for user in users )
49-
50- # Function to add a new user
51- def add_user (username , password ):
52- if not is_username_taken (username ):
53- users .append (User (username , password ))
54- return True
55- return False
56-
68+ # --- Authentication Operations ---
5769def signup_user (data ):
70+ """Register a new user with username and password"""
5871 if not data or "username" not in data or "password" not in data :
5972 return jsonify ({"error" : "Username and password are required" }), 400
6073
6174 if is_username_taken (data ["username" ]):
6275 return jsonify ({"error" : "Username already exists" }), 400
6376
6477 add_user (data ["username" ], data ["password" ])
65-
6678 return jsonify ({"message" : "Signup successful. Please log in to continue." }), 201
6779
68-
69- def login_user (data ):
70- if not data or "username" not in data or "password" not in data :
71- return jsonify ({"error" : "Username and password are required" }), 400
80+ def login_jwt (username , password ):
81+ """Authenticate user and return JWT tokens if valid"""
82+ user = validate_credentials (username , password )
83+ if not user :
84+ return jsonify ({"error" : "Invalid username or password" }), 401
7285
73- # Find user and validate credentials
74- user = next ((user for user in users if user .username == data ["username" ]), None )
75- if not user or not user .check_password (data ["password" ]):
86+ access_token , refresh_token = generate_jwt_token (username )
87+ return jsonify ({
88+ "message" : "Login successful" ,
89+ "access_token" : access_token ,
90+ "refresh_token" : refresh_token
91+ })
92+
93+ def login_session (username , password ):
94+ """Authenticate user and create session if valid"""
95+ user = validate_credentials (username , password )
96+ if not user :
7697 return jsonify ({"error" : "Invalid username or password" }), 401
7798
78- if auth_config .auth_method == AuthMethod .JWT :
79- access_token , refresh_token = generate_jwt_token (data ["username" ])
80- return jsonify ({
81- "message" : "Login successful" ,
82- "access_token" : access_token ,
83- "refresh_token" : refresh_token
84- })
99+ session ["authenticated" ] = True
100+ session ["username" ] = username
101+ return jsonify ({"message" : "Login successful" })
102+
103+ def logout_jwt (access_token , refresh_token ):
104+ """Invalidate JWT access and refresh tokens"""
105+ if not access_token or not refresh_token :
106+ return jsonify ({"error" : "Both access token and refresh token are required" }), 400
85107
86- elif auth_config .auth_method == AuthMethod .SESSION :
87- session ["authenticated" ] = True
88- session ["username" ] = data ["username" ]
89- return jsonify ({"message" : "Login successful" })
108+ blacklist_token (access_token )
109+ if refresh_token in refresh_tokens :
110+ del refresh_tokens [refresh_token ]
90111
91- return jsonify ({"error" : "Invalid authentication method" }), 500
92-
112+ return jsonify ({"message" : "Logout successful" })
93113
94- def logout_user ():
95- if auth_config .auth_method == AuthMethod .JWT :
96- return jsonify ({"message" : "Logout successful" })
97-
98- elif auth_config .auth_method == AuthMethod .SESSION :
99- session .clear ()
100- return jsonify ({"message" : "Logout successful" })
114+ def logout_session ():
115+ """Clear user session if authenticated"""
116+ if not session .get ("authenticated" ):
117+ return jsonify ({"error" : "Not authenticated" }), 401
101118
102- return jsonify ({"error" : "Invalid authentication method" }), 500
119+ session .clear ()
120+ return jsonify ({"message" : "Logout successful" })
0 commit comments