-
Notifications
You must be signed in to change notification settings - Fork 41
Expand file tree
/
Copy pathjwt-auth.ts
More file actions
73 lines (62 loc) · 2.11 KB
/
jwt-auth.ts
File metadata and controls
73 lines (62 loc) · 2.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
// Copyright (c) 2025 The Linux Foundation and each contributor.
// SPDX-License-Identifier: MIT
import { getCookie } from 'h3';
import jwt from 'jsonwebtoken';
import { isLocal } from '../utils/common';
import { DecodedOidcToken } from '~~/types/auth/auth-jwt.types';
const isJWT = (token: string) => {
const parts = token.split('.');
return parts.length === 3;
};
export default defineEventHandler(async (event) => {
const url = getRouterParam(event, '_') || event.node.req.url || '';
const protectedRoutes = [
'/api/report',
'/api/community/list',
'/api/security/update',
'/api/collection/community',
'/api/collection/like',
];
const protectedAndPermissionRoutes = ['/api/chat'];
const isProtectedRoute = [...protectedRoutes, ...protectedAndPermissionRoutes].some((route) =>
url.startsWith(route),
);
const isPermissionRequired = protectedAndPermissionRoutes.some((route) => url.startsWith(route));
if (!isProtectedRoute) {
return;
}
const config = useRuntimeConfig();
const oidcToken = getCookie(event, 'auth_oidc_token');
if (!oidcToken) {
throw createError({
statusCode: 401,
statusMessage: 'Authorization header required',
});
}
try {
// Verify and decode the OIDC token using the client secret
const decodedToken = jwt.verify(oidcToken, config.auth0ClientSecret, {
algorithms: ['HS256'],
}) as DecodedOidcToken;
if (decodedToken.original_id_token && isJWT(decodedToken.original_id_token)) {
event.context.user = decodedToken;
if (!isLocal && isPermissionRequired && !decodedToken.hasLfxInsightsPermission) {
throw createError({
statusCode: 401,
statusMessage: `User does not belong to ${config.lfxAuth0TokenClaimGroupName}`,
});
}
} else {
throw createError({
statusCode: 401,
statusMessage: 'Invalid token format',
});
}
} catch (jwtError) {
console.error('JWT verification failed:', jwtError);
throw createError({
statusCode: 401,
statusMessage: jwtError instanceof Error ? jwtError.message : 'Invalid JWT token',
});
}
});