Implement JWT payload parsing in socketService for user ID retrieval

- Enhanced the getSocketUserId function to extract user IDs from JWT tokens, improving user identification in socket connections.
- Added error handling for token parsing to ensure robustness against malformed tokens.

This update enhances the socket service's ability to manage user-specific connections by accurately retrieving user IDs from authentication tokens.
This commit is contained in:
Steven Enamakel
2026-01-29 08:13:11 +05:30
parent 60b4d2e446
commit 75eb2cd2f4
+22 -1
View File
@@ -7,8 +7,29 @@ import {
resetForUser,
} from "../store/socketSlice";
interface JwtPayload {
tgUserId?: string;
userId?: string;
sub?: string;
}
function getSocketUserId(): string {
return store.getState().user.user?._id ?? "__pending__";
const token = store.getState().auth.token;
if (!token) return "__pending__";
try {
const parts = token.split(".");
if (parts.length !== 3) return "__pending__";
const payloadBase64 = parts[1].replace(/-/g, "+").replace(/_/g, "/");
const payloadJson = atob(payloadBase64);
const payload = JSON.parse(payloadJson) as JwtPayload;
const id = payload.tgUserId || payload.userId || payload.sub;
return id || "__pending__";
} catch {
return "__pending__";
}
}
class SocketService {