Skip to content

Commit 2bf6324

Browse files
committed
Simplify UserId Extraction
1 parent e9b16ec commit 2bf6324

File tree

1 file changed

+12
-34
lines changed

1 file changed

+12
-34
lines changed

backend/question-service/controllers/historyController.ts

Lines changed: 12 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -1,41 +1,23 @@
1-
import { Request, Response } from 'express';
1+
import { Response } from 'express';
22
import jwt, { JwtPayload } from 'jsonwebtoken';
33
import historyEntryModel from '../models/HistoryEntry';
4-
import { Question } from 'models/Question';
4+
import { AuthenticatedRequest } from 'middlewares/auth';
55

66
const getErrorMessage = (error: unknown): string => {
77
if (error instanceof Error) return error.message;
88
return 'An unexpected error occurred';
99
};
1010

11-
const extractUserIdFromToken = (req: Request): string | null => {
12-
const authHeader = req.headers.authorization;
13-
if (!authHeader) {
14-
console.error('Authorization header missing');
15-
return null;
16-
}
17-
18-
const token = authHeader.split(' ')[1];
19-
if (!token) {
20-
console.error('Token missing from authorization header');
21-
return null;
22-
}
23-
24-
try {
25-
const decodedToken = jwt.verify(token, process.env.JWT_ACCESS_TOKEN_SECRET as string) as JwtPayload;
26-
if (decodedToken && typeof decodedToken === 'object' && 'id' in decodedToken) {
27-
return decodedToken.id as string;
28-
} else {
29-
console.error('Token payload does not contain user ID');
30-
return null;
31-
}
32-
} catch (error) {
33-
console.error('Token verification failed:', error);
11+
const extractUserIdFromToken = (req: AuthenticatedRequest): string | null => {
12+
const userId = req.userId;
13+
if (!userId) {
14+
console.error('userId missing - Token is likely invalid');
3415
return null;
3516
}
17+
return userId
3618
};
3719

38-
export const getUserHistoryEntries = async (req: Request, res: Response) => {
20+
export const getUserHistoryEntries = async (req: AuthenticatedRequest, res: Response) => {
3921
try {
4022
const userId = extractUserIdFromToken(req);
4123

@@ -68,24 +50,20 @@ export const getUserHistoryEntries = async (req: Request, res: Response) => {
6850
}
6951
};
7052

71-
export const createOrUpdateUserHistoryEntry = async (req: Request, res: Response) => {
53+
export const createOrUpdateUserHistoryEntry = async (req: AuthenticatedRequest, res: Response) => {
7254
try {
73-
// Extract userId from the token
7455
const userId = extractUserIdFromToken(req);
7556

7657
if (!userId) {
7758
return res.status(401).json({ error: 'Invalid or missing token' });
7859
}
7960

80-
// Destructure required fields from the request body
8161
const { questionId, roomId, attemptStartedAt, attemptCompletedAt, collaboratorId, attemptCode } = req.body;
8262

83-
// Validate required fields (optional but recommended)
8463
if (!roomId) {
8564
return res.status(400).json({ error: 'roomId is required' });
8665
}
8766

88-
// Attempt to find an existing history entry with the same userId and roomId
8967
const existingEntry = await historyEntryModel.findOne({ userId, roomId });
9068

9169
if (existingEntry) {
@@ -118,7 +96,7 @@ export const createOrUpdateUserHistoryEntry = async (req: Request, res: Response
11896
}
11997
};
12098

121-
export const deleteUserHistoryEntry = async (req: Request, res: Response) => {
99+
export const deleteUserHistoryEntry = async (req: AuthenticatedRequest, res: Response) => {
122100
try {
123101
const userId = extractUserIdFromToken(req);
124102

@@ -140,7 +118,7 @@ export const deleteUserHistoryEntry = async (req: Request, res: Response) => {
140118
}
141119
};
142120

143-
export const deleteUserHistoryEntries = async (req: Request, res: Response) => {
121+
export const deleteUserHistoryEntries = async (req: AuthenticatedRequest, res: Response) => {
144122
try {
145123
const userId = extractUserIdFromToken(req);
146124

@@ -160,7 +138,7 @@ export const deleteUserHistoryEntries = async (req: Request, res: Response) => {
160138
}
161139
};
162140

163-
export const deleteAllUserHistoryEntries = async (req: Request, res: Response) => {
141+
export const deleteAllUserHistoryEntries = async (req: AuthenticatedRequest, res: Response) => {
164142
try {
165143
const userId = extractUserIdFromToken(req);
166144

0 commit comments

Comments
 (0)