-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
61 lines (51 loc) · 1.77 KB
/
index.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
const jwt = require('jsonwebtoken');
const PLUGIN_NAME = 'jwt-generate-header';
const PLUGIN_ENVIRONMENT_SETTINGS = 'jwt-generate-header';
const JWT_PAYLOAD_HEADER_NAME = 'jwt-generate-header-payload'; //@deprecated
function cleanPluginHeader(context) {
context.request.removeHeader(JWT_PAYLOAD_HEADER_NAME);
}
function getPayload(context, jwtHeaderName) {
return (
context.request.getHeader(jwtHeaderName) ??
context.request.getHeader(JWT_PAYLOAD_HEADER_NAME)
);
}
module.exports = {
name: PLUGIN_NAME,
displayName: 'JwtHeaderGenerator',
description: 'Sign your header with JWT',
requestHooks: [
async context => {
console.log(`${PLUGIN_NAME} Running`);
const jwtSettings = context.request.getEnvironmentVariable(
PLUGIN_ENVIRONMENT_SETTINGS,
);
const jwtHeaderName = jwtSettings?.['jwt-header-name'];
const jwtSecret = jwtSettings?.['jwt-secret'];
const jwtAlgorithm = jwtSettings?.['jwt-algorithm'] ?? 'HS256';
const jwtExpiresIn = jwtSettings?.['jwt-expiresIn'];
if (!jwtSettings || !jwtHeaderName || !jwtSecret) {
cleanPluginHeader(context);
console.log(`${PLUGIN_NAME} Missing required parameters`);
return;
}
const jwtPayload = getPayload(context, jwtHeaderName);
if (!jwtPayload) {
console.log(`${PLUGIN_NAME} No jwt-payload found`);
return;
}
try {
let sig = jwt.sign(JSON.parse(jwtPayload), jwtSecret, {
algorithm: jwtAlgorithm,
...(jwtExpiresIn ? { expiresIn: jwtExpiresIn } : {}),
});
context.request.setHeader(jwtHeaderName, `${sig}`);
} catch (error) {
console.log(`${PLUGIN_NAME} Error `, error);
} finally {
cleanPluginHeader(context);
}
},
],
};