-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathworkers.js
83 lines (69 loc) · 1.94 KB
/
workers.js
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
74
75
76
77
78
79
80
81
82
83
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
async function handleRequest(request) {
const token = request.headers.get('Authorization');
if (!token) {
return new Response('Unauthorized', {
status: 401,
statusText: 'Unauthorized'
});
}
// Verify the JWT token
const decodedToken = verifyJwtToken(token);
if (!decodedToken) {
return new Response('Unauthorized', {
status: 401,
statusText: 'Unauthorized'
});
}
// Get the user ID from the decoded token
const userId = decodedToken.sub;
// Look up the API key for the user
const apiKey = await getApiKeyForUser(userId);
if (!apiKey) {
return new Response('Unauthorized', {
status: 401,
statusText: 'Unauthorized'
});
}
// Check if the API key in the request matches the API key for the user
const requestApiKey = request.headers.get('X-Api-Key');
if (requestApiKey !== apiKey) {
return new Response('Unauthorized', {
status: 401,
statusText: 'Unauthorized'
});
}
// Access to the API is granted, process the request
// ...
return new Response('API Access Granted', {
status: 200,
statusText: 'OK'
});
}
function verifyJwtToken(token) {
// Verify the JWT token using a library such as jsonwebtoken
// ...
return decodedToken;
}
async function getApiKeyForUser(userId) {
// Call an API or retrieve data from a database to get the API key for the user
// ...
async function getApiKeyForUser(userId) {
const API_URL = `https://<YOUR_AUTH0_DOMAIN>/api/v2/users/${userId}`;
const API_TOKEN = '<YOUR_AUTH0_API_TOKEN>';
const response = await fetch(API_URL, {
method: 'GET',
headers: {
'Authorization': `Bearer ${API_TOKEN}`
}
});
if (!response.ok) {
throw new Error(`getApiKeyForUser failed with status ${response.status}`);
}
const user = await response.json();
return user['api_key'];
}
return apiKey;
}