fix: decode JWT in middleware to populate req.user for RolesGuard

Kong validates the JWT but doesn't populate req.user on the backend.
The middleware now decodes the JWT payload to extract user info (id,
email, tenantId, roles) so RolesGuard can check role-based access.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
hailin 2026-02-22 00:25:32 -08:00
parent f393a07092
commit 52b85f085e
1 changed files with 19 additions and 0 deletions

View File

@ -6,6 +6,25 @@ export class TenantContextMiddleware implements NestMiddleware {
use(req: any, res: any, next: () => void) {
const tenantId = req.headers?.['x-tenant-id'] as string;
// Decode JWT to populate req.user for RolesGuard
const authHeader = req.headers?.['authorization'] as string;
if (authHeader?.startsWith('Bearer ')) {
try {
const token = authHeader.slice(7);
const payload = JSON.parse(
Buffer.from(token.split('.')[1], 'base64').toString(),
);
req.user = {
id: payload.sub,
email: payload.email,
tenantId: payload.tenantId,
roles: payload.roles || [],
};
} catch {
// Ignore decode errors - JWT validation is handled by Kong
}
}
if (!tenantId) {
return next();
}