Skip to content

Commit 8fa5c48

Browse files
committed
fix middleware + format
1 parent efa0276 commit 8fa5c48

File tree

1 file changed

+58
-3
lines changed

1 file changed

+58
-3
lines changed

backend/middleware/auth.ts

Lines changed: 58 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,18 +17,73 @@ export const authenticateToken = async (
1717
return;
1818
}
1919

20-
next();
20+
const token = authHeader.substring(7);
21+
22+
const verifiedToken = await verifyToken(token, {
23+
secretKey: process.env.CLERK_SECRET_KEY!,
24+
clockSkewInMs: 5000,
25+
});
26+
27+
console.log('Token verification result:', {
28+
userId: verifiedToken.sub,
29+
sessionId: verifiedToken.sid,
30+
path: req.path,
31+
method: req.method,
32+
});
33+
34+
const adminUser = await prisma.adminUser.findUnique({
35+
where: { clerkId: verifiedToken.sub },
36+
});
37+
38+
if (adminUser) {
39+
console.log('Admin user lookup:', {
40+
clerkId: verifiedToken.sub,
41+
found: true,
42+
});
43+
44+
req.user = {
45+
id: adminUser.id,
46+
clerkId: adminUser.clerkId,
47+
role: 'ADMIN',
48+
email: adminUser.email,
49+
name: adminUser.name,
50+
};
51+
} else {
52+
const organization = await prisma.organization.findUnique({
53+
where: { clerkId: verifiedToken.sub },
54+
});
55+
56+
console.log('Organization lookup:', {
57+
clerkId: verifiedToken.sub,
58+
found: !!organization,
59+
role: organization?.role,
60+
});
61+
62+
if (organization) {
63+
req.user = {
64+
id: organization.id,
65+
clerkId: organization.clerkId,
66+
role: organization.role,
67+
email: organization.email,
68+
name: organization.name,
69+
};
70+
}
71+
}
72+
next();
73+
} catch (error: any) {
74+
console.error('Token verification error:', error.message);
75+
res.status(401).json({ error: 'Invalid or expired token' });
76+
}
2177
};
2278

2379
export const requireAdmin = async (
2480
req: AuthenticatedRequest,
2581
res: Response,
2682
next: NextFunction
2783
): Promise<void> => {
28-
const auth = getAuth(req);
2984
if (!isAdmin(req.user?.role)) {
3085
res.status(403).json({ error: 'Admin access required' });
3186
return;
3287
}
3388
next();
34-
};
89+
};

0 commit comments

Comments
 (0)