Skip to content

Commit 07cdbd2

Browse files
authored
feat: add endpoint to retrieve online users with session information (#70)
- Implemented a new API endpoint `/online` for admin users to fetch all online users and their details based on active sessions stored in Redis. - Enhanced session handling by decoding JWT tokens to extract user IDs and retrieve corresponding user data from the database. - Added error handling for session processing to ensure robustness in user data retrieval.
1 parent 0209a51 commit 07cdbd2

File tree

1 file changed

+49
-1
lines changed

1 file changed

+49
-1
lines changed

src/backend/routers/user_router.py

Lines changed: 49 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,12 @@
11
import os
2+
import json
23
from uuid import UUID
34

45
import posthog
6+
import jwt
57
from fastapi import APIRouter, Depends, HTTPException
68

7-
from config import get_redis_client, FRONTEND_URL
9+
from config import get_redis_client, get_jwks_client, OIDC_CLIENT_ID, FRONTEND_URL
810
from database import get_user_service
911
from database.service import UserService
1012
from dependencies import UserSession, require_admin, require_auth
@@ -99,6 +101,52 @@ async def get_user_count(
99101
return {"active_sessions": session_count }
100102

101103

104+
@user_router.get("/online")
105+
async def get_online_users(
106+
_: bool = Depends(require_admin),
107+
user_service: UserService = Depends(get_user_service)
108+
):
109+
"""Get all online users with their information (admin only)"""
110+
client = get_redis_client()
111+
112+
# Get all session keys
113+
session_keys = client.keys("session:*")
114+
115+
# Extract user IDs from sessions and fetch user data
116+
online_users = []
117+
for key in session_keys:
118+
session_data = client.get(key)
119+
if session_data:
120+
try:
121+
# Parse session data
122+
session_json = json.loads(session_data)
123+
124+
# Extract user ID from token
125+
token_data = session_json.get('access_token')
126+
if token_data:
127+
# Decode JWT token to get user ID
128+
jwks_client = get_jwks_client()
129+
signing_key = jwks_client.get_signing_key_from_jwt(token_data)
130+
decoded = jwt.decode(
131+
token_data,
132+
signing_key.key,
133+
algorithms=["RS256"],
134+
audience=OIDC_CLIENT_ID,
135+
)
136+
137+
# Get user ID from token
138+
user_id = UUID(decoded.get('sub'))
139+
140+
# Fetch user data from database
141+
user_data = await user_service.get_user(user_id)
142+
if user_data:
143+
online_users.append(user_data)
144+
except Exception as e:
145+
print(f"Error processing session {key}: {str(e)}")
146+
continue
147+
148+
return {"online_users": online_users, "count": len(online_users)}
149+
102150
@user_router.get("/{user_id}")
103151
async def get_user(
104152
user_id: UUID,

0 commit comments

Comments
 (0)