-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
76 lines (63 loc) · 1.91 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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
const jwt = require('jsonwebtoken');
const JWT_PRIVATE_KEY = `-----BEGIN RSA PRIVATE KEY-----\n${process.env.JWT_PRIVATE_KEY}\n-----END RSA PRIVATE KEY-----`;
const BACKEND_URL = process.env.BACKEND_URL; // Internal ALB for ECS
/**
*
* @param {number} statusCode
* @param {any} body
* @returns {Promise<AWSLambda.APIGatewayProxyResult}
*/
const result = (statusCode, body = null) => {
return {
headers: { 'content-type': 'application/json' },
statusCode,
body: JSON.stringify(body),
};
};
/**
* @param {AWSLambda.APIGatewayEvent} event
*/
const getNationalIdFromEvent = (event) => {
return event.queryStringParameters?.nationalId;
};
const getClientIdByNationalId = async (nationalId) => {
const { id } = await fetch(
`${BACKEND_URL}/clients/identification?nationalId=${nationalId}`,
{ method: 'POST' }
).then((res) => res.json());
if (!id) throw 'No ID returned from service:' + id;
console.log('Succesfully retrived client', id);
return id;
};
/**
* @param {AWSLambda.APIGatewayEvent} event
* @returns {Promise<AWSLambda.APIGatewayProxyResult}
*/
exports.handler = async (event) => {
const nationalId = await getNationalIdFromEvent(event);
if (!nationalId) {
return result(400, { message: 'Missing national ID' });
}
try {
const clientId = await getClientIdByNationalId(nationalId);
try {
const token = jwt.sign({ sub: clientId.toString() }, JWT_PRIVATE_KEY, {
expiresIn: '1h',
algorithm: 'RS256',
});
return result(200, { token });
} catch (error) {
console.error('Error while generating token:', error);
return result(500, {
message: 'Error while generating token',
error: error?.message,
});
}
} catch (error) {
console.error('Error while verifying national ID:', error);
return result(500, {
message: 'Error while verifying national ID',
error: error?.message,
});
}
};