ChandimaPrabath commited on
Commit
f5e2ee2
·
1 Parent(s): d022d1e

test validation update

Browse files
Files changed (1) hide show
  1. main.py +63 -29
main.py CHANGED
@@ -172,6 +172,56 @@ async def init_system_user():
172
  print("System user already exists, continuing...")
173
  else:
174
  raise e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
175
 
176
  @root_router.get("/", status_code=status.HTTP_200_OK)
177
  async def root():
@@ -260,40 +310,24 @@ async def logout(user_id: str, token: str):
260
 
261
  @auth_router.get("/validate", response_model=TokenResponse)
262
  async def validate_token(user_id: str, token: str, user_agent: str = Header(...)):
263
- # Query to validate session by user_id, token, and device
264
- session_query = (
265
- supabase.table("sessions")
266
- .select("*")
267
- .eq("user_id", user_id)
268
- .eq("token", token)
269
- .eq("device", user_agent)
270
- .execute()
271
- )
272
-
273
- # If no session found, raise unauthorized error
274
- if not session_query.data:
275
- raise HTTPException(
276
- status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token"
277
- )
278
-
279
- session = session_query.data[0]
280
-
281
- # Get the current time (UTC) with timezone awareness
282
- current_time = datetime.now(timezone.utc)
283
 
284
- # Parse the 'expires' field from the session as an offset-aware datetime
285
- session_expiry = datetime.fromisoformat(session["expires"])
 
 
286
 
287
- # Check if the token has expired
288
- if session_expiry <= current_time:
289
- # Delete the session if expired
290
- supabase.table("sessions").delete().eq("user_id", user_id).eq("token", token).execute()
291
- raise HTTPException(
292
- status_code=status.HTTP_401_UNAUTHORIZED, detail="Token expired"
293
- )
294
 
 
295
  return TokenResponse(access_token=token)
296
 
 
297
  @auth_router.get("/search-users", response_model=List[str])
298
  async def search_users(query: str):
299
  users = supabase.table("users").select("username").ilike("username", f"%{query}%").execute()
 
172
  print("System user already exists, continuing...")
173
  else:
174
  raise e
175
+
176
+ async def validate_session(user_id: str, token: str, user_agent: str) -> Optional[dict]:
177
+ """
178
+ Validates the session for the given user_id, token, and user_agent.
179
+
180
+ Args:
181
+ user_id: The user ID associated with the session.
182
+ token: The token to validate.
183
+ user_agent: The user agent/device identifier.
184
+
185
+ Returns:
186
+ The session data if valid.
187
+
188
+ Raises:
189
+ HTTPException: If the session is invalid or the token is expired.
190
+ """
191
+ # Query to validate session by user_id, token, and device
192
+ session_query = (
193
+ supabase.table("sessions")
194
+ .select("*")
195
+ .eq("user_id", user_id)
196
+ .eq("token", token)
197
+ .eq("device", user_agent)
198
+ .execute()
199
+ )
200
+
201
+ # If no session found, raise unauthorized error
202
+ if not session_query.data:
203
+ raise HTTPException(
204
+ status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token"
205
+ )
206
+
207
+ session = session_query.data[0]
208
+
209
+ # Get the current time (UTC) with timezone awareness
210
+ current_time = datetime.now(timezone.utc)
211
+
212
+ # Parse the 'expires' field from the session as an offset-aware datetime
213
+ session_expiry = datetime.fromisoformat(session["expires"])
214
+
215
+ # Check if the token has expired
216
+ if session_expiry <= current_time:
217
+ # Delete the session if expired
218
+ supabase.table("sessions").delete().eq("user_id", user_id).eq("token", token).execute()
219
+ raise HTTPException(
220
+ status_code=status.HTTP_401_UNAUTHORIZED, detail="Token expired"
221
+ )
222
+
223
+ return session
224
+
225
 
226
  @root_router.get("/", status_code=status.HTTP_200_OK)
227
  async def root():
 
310
 
311
  @auth_router.get("/validate", response_model=TokenResponse)
312
  async def validate_token(user_id: str, token: str, user_agent: str = Header(...)):
313
+ """
314
+ Route to validate a token based on user_id, token, and user agent.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
315
 
316
+ Args:
317
+ user_id: The user ID associated with the token.
318
+ token: The token to validate.
319
+ user_agent: The user agent (from request header).
320
 
321
+ Returns:
322
+ TokenResponse: The validated token response.
323
+ """
324
+ # Use the helper function to validate the session
325
+ await validate_session(user_id=user_id, token=token, user_agent=user_agent)
 
 
326
 
327
+ # Return the token if validation succeeds
328
  return TokenResponse(access_token=token)
329
 
330
+
331
  @auth_router.get("/search-users", response_model=List[str])
332
  async def search_users(query: str):
333
  users = supabase.table("users").select("username").ilike("username", f"%{query}%").execute()