Skip to content

Commit bc53e16

Browse files
committed
refactor: encapsulate token verification logic in a separate function
1 parent bcc7231 commit bc53e16

1 file changed

Lines changed: 10 additions & 8 deletions

File tree

backend/src/middleware/auth.ts

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -23,19 +23,21 @@ const extractToken = (authHeader: unknown): string | null => {
2323
return parts[1];
2424
};
2525

26+
const verifyAuth = (authHeader: unknown): { userId: string; username: string } => {
27+
const token = extractToken(authHeader);
28+
if (!token) {
29+
throw new Error('Missing token');
30+
}
31+
return jwt.verify(token, JWT_SECRET) as { userId: string; username: string };
32+
};
33+
2634
export const authenticate = async (
2735
req: AuthRequest,
2836
res: Response,
2937
next: NextFunction
3038
) => {
3139
try {
32-
const token = extractToken(req.headers.authorization);
33-
34-
if (!token) {
35-
return res.status(401).json({ error: 'Yetkilendirme gerekli' });
36-
}
37-
38-
const decoded = jwt.verify(token, JWT_SECRET) as { userId: string; username: string };
40+
const decoded = verifyAuth(req.headers.authorization);
3941

4042
const user = await prisma.user.findUnique({
4143
where: { id: decoded.userId },
@@ -48,7 +50,7 @@ export const authenticate = async (
4850

4951
req.user = user;
5052
next();
51-
} catch (error) {
53+
} catch {
5254
return res.status(401).json({ error: 'Geçersiz token' });
5355
}
5456
};

0 commit comments

Comments
 (0)