Skip to content

Commit e88094f

Browse files
committed
PEER-219: Refactor localstorage userId
Signed-off-by: SeeuSim <[email protected]>
1 parent b7be5d8 commit e88094f

File tree

12 files changed

+64
-26
lines changed

12 files changed

+64
-26
lines changed

backend/user/src/controllers/auth-check/index.ts

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
1+
import { eq } from 'drizzle-orm';
12
import { StatusCodes } from 'http-status-codes';
23

34
import { COOKIE_NAME, decodeCookie, isCookieValid } from '@/lib/cookies';
5+
import { db, users } from '@/lib/db';
46
import { logger } from '@/lib/utils';
57
import { IRouteHandler } from '@/types';
68

@@ -13,9 +15,16 @@ export const checkIsAuthed: IRouteHandler = async (req, res) => {
1315
logger.info(
1416
'[/auth-check/check-is-authed]: Expires At ' + new Date(expireTimeInMillis).toLocaleString()
1517
);
18+
const user = await db
19+
.select({ name: users.username })
20+
.from(users)
21+
.where(eq(users.id, decoded.id))
22+
.limit(1);
1623
return res.status(StatusCodes.OK).json({
1724
message: 'OK',
1825
expiresAt: expireTimeInMillis,
26+
userId: decoded.id,
27+
username: user.length > 0 ? user[0].name : undefined,
1928
});
2029
}
2130

frontend/src/components/blocks/interview/editor.tsx

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ import {
1616
import { Skeleton } from '@/components/ui/skeleton';
1717
import { getTheme, type IEditorTheme, languages, themeOptions } from '@/lib/editor/extensions';
1818
import { useCollab } from '@/lib/hooks/use-collab';
19+
import { useUser } from '@/stores/auth-store';
1920

2021
import { CompleteDialog } from './room/complete-dialog';
2122
import { OtherUserCompletingDialog } from './room/other-user-completing-dialog';
@@ -31,10 +32,10 @@ type EditorProps = {
3132
};
3233

3334
export const Editor = ({ questionId, room, onAIClick, onPartnerClick }: EditorProps) => {
35+
const { userId } = useUser();
3436
const { height } = useWindowSize();
3537
const [theme, setTheme] = useState<IEditorTheme>('vscodeDark');
3638
const {
37-
userId,
3839
editorRef,
3940
extensions,
4041
language,

frontend/src/components/blocks/interview/partner-chat.tsx

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import React, { useState } from 'react';
22

33
import { useChat } from '@/lib/hooks/use-chat';
4-
import { getUserId } from '@/services/user-service';
4+
import { useUser } from '@/stores/auth-store';
55

66
import { ChatLayout } from './chat/chat-layout';
77

@@ -12,6 +12,7 @@ interface PartnerChatProps {
1212
}
1313

1414
export const PartnerChat: React.FC<PartnerChatProps> = ({ isOpen, onClose, roomId }) => {
15+
const { userId } = useUser();
1516
const { messages, sendMessage, connected, error } = useChat({ roomId });
1617
const [isLoading, setIsLoading] = useState(false);
1718

@@ -27,7 +28,7 @@ export const PartnerChat: React.FC<PartnerChatProps> = ({ isOpen, onClose, roomI
2728
onClose={onClose}
2829
messages={messages.map((msg) => ({
2930
text: msg.message,
30-
isUser: msg.senderId === getUserId(),
31+
isUser: msg.senderId === userId,
3132
timestamp: new Date(msg.createdAt),
3233
}))}
3334
onSend={handleSend}

frontend/src/components/blocks/route-guard.tsx

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import {
1212
import { usePageTitle } from '@/lib/hooks/use-page-title';
1313
import { ROUTES, UNAUTHED_ROUTES } from '@/lib/routes';
1414
import { checkIsAuthed } from '@/services/user-service';
15+
import { AuthStoreProvider } from '@/stores/auth-store';
1516

1617
import { Loading } from './loading';
1718

@@ -55,9 +56,15 @@ export const RouteGuard = () => {
5556
}
5657

5758
setIsLoading(false);
58-
}, []);
59+
}, [authedPayload]);
5960
usePageTitle(path);
60-
return isLoading ? <Loading /> : <Outlet />;
61+
return (
62+
<AuthStoreProvider
63+
value={{ userId: authedPayload.userId ?? '', username: authedPayload.userName ?? '' }}
64+
>
65+
{isLoading ? <Loading /> : <Outlet />}
66+
</AuthStoreProvider>
67+
);
6168
}}
6269
</Await>
6370
</Suspense>

frontend/src/lib/hooks/use-chat.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import { useCallback, useEffect, useRef, useState } from 'react';
22
import { io, Socket } from 'socket.io-client';
33

44
import { CHAT_SOCKET } from '@/services/api-clients';
5-
import { getUserId } from '@/services/user-service';
5+
import { useUser } from '@/stores/auth-store';
66
import { Message } from '@/types/chat-types';
77

88
const WS_EVENT = {
@@ -24,7 +24,7 @@ interface UseChatProps {
2424
}
2525

2626
export const useChat = ({ roomId }: UseChatProps) => {
27-
const [userId] = useState(getUserId());
27+
const { userId } = useUser();
2828
const [messages, setMessages] = useState<Message[]>([]);
2929
const [connected, setConnected] = useState(false);
3030
const [error, setError] = useState<string | null>(null);

frontend/src/lib/hooks/use-collab.ts

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ import * as Y from 'yjs';
88

99
import { extensions as baseExtensions, getLanguage } from '@/lib/editor/extensions';
1010
import { COLLAB_WS } from '@/services/api-clients';
11-
import { getUserId } from '@/services/user-service';
11+
import { useUser } from '@/stores/auth-store';
1212
import type { IYjsUserState } from '@/types/collab-types';
1313

1414
// credit: https://github.com/yjs/y-websocket
@@ -29,7 +29,7 @@ const getRandomColor = () => {
2929

3030
// TODO: Test if collab logic works
3131
export const useCollab = (roomId: string) => {
32-
const [userId] = useState(getUserId());
32+
const { userId, username } = useUser();
3333
const editorRef = useRef<ReactCodeMirrorRef>(null);
3434
const [sharedDocRef, setSharedDocRef] = useState<Y.Map<unknown>>();
3535
const [extensions, setExtensions] = useState<Array<Extension>>(baseExtensions);
@@ -95,8 +95,8 @@ export const useCollab = (roomId: string) => {
9595
const { color, light } = getRandomColor();
9696
// TODO: Get user name, ID
9797
const userState: IYjsUserState['user'] = {
98-
name: `Anon`,
99-
userId: userId ?? 'null',
98+
name: username,
99+
userId,
100100
color,
101101
colorLight: light,
102102
};
@@ -150,7 +150,6 @@ export const useCollab = (roomId: string) => {
150150
setCode,
151151
members,
152152
isLoading,
153-
userId,
154153
isCompleting,
155154
setIsCompleting,
156155
cursorPosition,

frontend/src/routes/interview/[room]/main.tsx

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import { Editor } from '@/components/blocks/interview/editor';
88
import { PartnerChat } from '@/components/blocks/interview/partner-chat';
99
import { QuestionDetails } from '@/components/blocks/questions/details';
1010
import { Card } from '@/components/ui/card';
11+
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
1112
import { useCrumbs } from '@/lib/hooks';
1213
import { questionDetailsQuery } from '@/lib/queries/question-details';
1314
import { ROUTES } from '@/lib/routes';
@@ -50,8 +51,18 @@ export const InterviewRoom = () => {
5051
<WithNavBanner crumbs={crumbs}>
5152
<div className='flex flex-1 overflow-hidden'>
5253
<Card className='border-border m-4 flex w-[500px] overflow-hidden p-4 md:w-2/5'>
53-
<QuestionDetails {...{ questionDetails }} />
54+
<Tabs defaultValue='details'>
55+
<TabsList className=''>
56+
<TabsTrigger value='details'>Question Details</TabsTrigger>
57+
<TabsTrigger value='attempts'>Past Attempts</TabsTrigger>
58+
</TabsList>
59+
<TabsContent value='details' className='flex h-full'>
60+
<QuestionDetails {...{ questionDetails }} />
61+
</TabsContent>
62+
<TabsContent value='attempts' className='flex h-full' />
63+
</Tabs>
5464
</Card>
65+
5566
<div className='flex w-full'>
5667
<Editor
5768
questionId={questionId}

frontend/src/routes/match/logic.ts

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ import { z } from 'zod';
77

88
import { requestMatch } from '@/services/match-service';
99
import { fetchDifficulties, fetchTopics } from '@/services/question-service';
10-
import { getUserId } from '@/services/user-service';
10+
import { useUser } from '@/stores/auth-store';
1111

1212
export interface MatchFormData {
1313
selectedTopics: string[];
@@ -44,8 +44,7 @@ const formSchema = z.object({
4444
export type IRequestMatchFormSchema = z.infer<typeof formSchema>;
4545

4646
export const useRequestMatchForm = () => {
47-
// TODO: Set on RouteGuard is-authed request and then query Context API
48-
const userId = getUserId() as string;
47+
const { userId } = useUser();
4948

5049
const [socketPort, setSocketPort] = useState('');
5150

frontend/src/routes/match/waiting-room/waiting.tsx

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ import { ROUTES } from '@/lib/routes';
88
import { MATCHING_EVENT, WS_EVENT } from '@/lib/ws';
99
import { MATCHING_SOCKET } from '@/services/api-clients';
1010
import { cancelMatch } from '@/services/match-service';
11-
import { getUserId } from '@/services/user-service';
11+
import { useUser } from '@/stores/auth-store';
1212
import { useMatchRequest } from '@/stores/match-request-store';
1313

1414
import { UI_STATUS } from './constants';
@@ -25,6 +25,7 @@ type IWaitingRoomUIState = {
2525
};
2626

2727
export const WaitingRoom = ({ socketPort, setIsModalOpen }: IWaitingRoomProps) => {
28+
const { userId } = useUser();
2829
const navigate = useNavigate();
2930
const { values } = useMatchRequest();
3031
const [{ connected, canCancel, uiState }, setUIState] = useState<IWaitingRoomUIState>({
@@ -33,7 +34,7 @@ export const WaitingRoom = ({ socketPort, setIsModalOpen }: IWaitingRoomProps) =
3334
uiState: UI_STATUS.WAITING_STATUS,
3435
});
3536
const { mutate: sendCancelRequest, isPending: isCancelling } = useMutation({
36-
mutationFn: cancelMatch,
37+
mutationFn: () => cancelMatch(userId),
3738
onSuccess: () => {
3839
// TODO: Add toaster notif or cancel success UI
3940
setIsModalOpen(false);
@@ -100,7 +101,7 @@ export const WaitingRoom = ({ socketPort, setIsModalOpen }: IWaitingRoomProps) =
100101

101102
socket.emit(WS_EVENT.START_QUEUING, {
102103
roomId: socketPort,
103-
userId: getUserId(),
104+
userId,
104105
topic: values?.selectedTopics,
105106
difficulty: values?.difficulty,
106107
});

frontend/src/services/match-service.ts

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
import { IRequestMatchResponse } from '@/types/match-types';
22

33
import { matchApiClient } from './api-clients';
4-
import { getUserId } from './user-service';
54

65
const MATCHING_SERVICE_ROUTES = {
76
REQUEST_MATCH: '/match/request',
@@ -33,6 +32,6 @@ export const requestMatch = (
3332
});
3433
};
3534

36-
export const cancelMatch = () => {
37-
return matchApiClient.post(MATCHING_SERVICE_ROUTES.CANCEL_MATCH, { userId: getUserId() });
35+
export const cancelMatch = (userId: string) => {
36+
return matchApiClient.post(MATCHING_SERVICE_ROUTES.CANCEL_MATCH, { userId });
3837
};

0 commit comments

Comments
 (0)