-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.js
More file actions
421 lines (361 loc) · 13.6 KB
/
index.js
File metadata and controls
421 lines (361 loc) · 13.6 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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
const express = require('express');
const dotenv = require('dotenv');
const cors = require('cors');
const { v4: uuidv4, validate: isUUID } = require('uuid');
const fs = require('node:fs');
const app = express();
dotenv.config();
app.use(cors())
// Middleware to handle raw body data
app.use(express.raw({ type: '*/*' }));
const defaultHeader = {
'Content-Type': "application/json",
'x-api-key': process.env.API_KEY,
'api-version': '1.0'
};
// Admin Token + ApiKey are needed for approving
const adminHeader = {
'Content-Type': "application/json",
'x-api-key': process.env.API_KEY,
'X-Incode-Hardware-Id': process.env.ADMIN_TOKEN,
'api-version': '1.0'
};
// Call Incode's `omni/start` API to create an Incode session which will include a
// token in the JSON response.
app.get('/start', async (req, res) => {
let uniqueId = req.query.uniqueId;
// We retrieve a session that was already started and from which we have stored.
if (uniqueId) {
try {
const { token } = readSession(uniqueId);
// The interviewId is also saved in the session, but you shouldn't return it to the frontend.
res.json({token, uniqueId});
} catch (e) {
res.status(400).send({success:false, error: e.message});
}
return;
}
// We create a new random uniqueId to associate the session
uniqueId = uuidv4();
const startUrl = `${process.env.API_URL}/omni/start`;
const startParams = {
configurationId: process.env.FLOW_ID,
language: "en-US",
// redirectionUrl: "https://example.com?custom_parameter=some+value",
// externalCustomerId: "the id of the customer in your system",
};
try{
const startData = await doPost(startUrl, startParams, defaultHeader);
const {token, interviewId} = startData;
// To the session we save the interviewId for internal purposes
writeSession(uniqueId, {token, interviewId, uniqueId});
// But we never return it to the frontend
res.json({token, uniqueId});
} catch(e) {
console.log(e.message);
res.status(500).send({success:false, error: e.message});
return;
}
});
// Calls incodes `omni/start` and then with the token calls `0/omni/onboarding-url`
// to retrieve the unique onboarding-url for the newly created session.
app.get('/onboarding-url', async (req, res) => {
const startUrl = `${process.env.API_URL}/omni/start`;
const startParams = {
configurationId: process.env.FLOW_ID,
language: "en-US",
// redirectionUrl: "https://example.com?custom_parameter=some+value",
// externalCustomerId: "the id of the customer in your system",
};
let startData = null;
try{
startData = await doPost(startUrl, startParams, defaultHeader);
} catch(e) {
console.log(e.message);
res.status(500).send({success:false, error: e.message});
return;
}
const {token, interviewId} = startData;
const onboardingHeader = {...defaultHeader};
onboardingHeader['X-Incode-Hardware-Id'] = startData.token;
const onboardingUrl = `${process.env.API_URL}/0/omni/onboarding-url`;
let onboardingUrlData= null;
try{
onboardingUrlData = await doGet(onboardingUrl, {}, onboardingHeader);
} catch(e) {
console.log(e.message);
res.status(500).send({success:false, error: e.message});
return;
}
session ={ success:true, token, interviewId, url: onboardingUrlData.url }
res.json(session);
});
// Checks if an onboarding has been finished against a local method of Storage
app.get('/onboarding-status', async (req, res) => {
// Get the interviewId from query parameters
const interviewId = req.query.interviewId;
if (!interviewId) {
res.status(400).send({success:false, error:'Missing required parameter interviewId'});
return;
}
const statusURL = `${process.env.API_URL}/omni/get/onboarding/status`;
try {
const response = await doGet(statusURL, {id:interviewId}, adminHeader);
onboardingStatus = response.onboardingStatus;
res.status(200).send({success:true, onboardingStatus})
} catch(e) {
console.log(e.message);
res.status(500).send({success:false, error: e.message});
}
});
// Checks if an onboarding has been finished against a local method of Storage
app.get('/fetch-score', async (req, res) => {
// Get the interviewId from query parameters
const interviewId = req.query.interviewId;
if (!interviewId) {
res.status(400).send({success:false, error:'Missing required parameter interviewId'});
return;
}
//Get the token of the session from the headers
let token = req.headers["x-token"];
if (!token) {
res.status(400).send({success:false, error:'Missing required header X-Token'});
return;
}
scoreHeader = {...defaultHeader};
scoreHeader['X-Incode-Hardware-Id'] = token;
//Let's find out the score
const scoreUrl = `${process.env.API_URL}/omni/get/score`;
let onboardingScore = null
try {
onboardingScore = await doGet(scoreUrl, {id:interviewId}, scoreHeader);
} catch(e) {
console.log(e.message);
res.status(500).send({success:false, error: e.message});
return;
}
// Onboarding Score has a lot of information that might interest you
// https://docs.incode.com/docs/omni-api/api/onboarding#fetch-scores
if (onboardingScore?.overall?.status==='OK'){
// Session passed with OK here you would procced to save user data into
// your database or any other process your bussiness logic requires.
console.log('User passed with OK');
res.json({success:true, score: 'OK'});
} else {
console.log("User didn't passed");
res.json({success:true, score: 'FAIL'});
}
});
// Webhook to receive onboarding status, configure it in
// incode dasboard > settings > webhook > onboarding status
app.post('/webhook', async (req, res) => {
// Handle the received webhook data
const webhookData = JSON.parse(req.body.toString());
// Last Step of the onboarding, now you can ask for the score.
if(webhookData.onboardingStatus==="ONBOARDING_FINISHED"){
console.log('User finished onboarding');
const scoreUrl = `${process.env.API_URL}/omni/get/score`;
let onboardingScore = {}
try {
onboardingScore = await doGet(scoreUrl, {id:webhookData.interviewId}, adminHeader);
} catch(e) {
console.log(e.message);
}
// Onboarding Score has a lot of information that might interest you
// https://docs.incode.com/docs/omni-api/api/onboarding#fetch-scores
if (onboardingScore?.overall?.status==='OK'){
// Session passed with OK here you would procced to save user data into
// your database or any other process your bussiness logic requires.
console.log('User passed with OK');
} else {
console.log('User did not passed');
}
}
// Process received data (for demonstration, just returning the received payload
// and include the timestamp)
response = {
timestamp: new Date().toISOString().slice(0, 19).replace('T', ' '),
success: true,
data: webhookData
}
res.status(200).send(response);
// Write to a log so you can debug it.
console.log(response);
});
// Webhook to receive onboarding status, configure it in
// incode dasboard > settings > webhook > onboarding status
// This endpoint will auto-approve(create an identity) for
// any sessions that PASS.
app.post('/approve', async (req, res) => {
// Handle the received webhook data
const webhookData = JSON.parse(req.body.toString());
if(webhookData.onboardingStatus==="ONBOARDING_FINISHED"){
// Admin Token + ApiKey are needed for approving and fetching scores
const adminHeader = {
'Content-Type': "application/json",
//'x-api-key': process.env.API_KEY,
'X-Incode-Hardware-Id': process.env.ADMIN_TOKEN,
'api-version': '1.0'
};
const scoreUrl = `${process.env.API_URL}/omni/get/score`;
const onboardingScore = await doGet(scoreUrl, {id:webhookData.interviewId}, adminHeader);
//Onboarding Score has a lot of information that might interest you https://docs.incode.com/docs/omni-api/api/onboarding#fetch-scores
if (onboardingScore.overall.status==='OK'){
const approveUrl = `${process.env.API_URL}/omni/process/approve?interviewId=${webhookData.interviewId}`;
const identityData = await doPost(approveUrl,{}, adminHeader);
response = {
timestamp: new Date().toISOString().slice(0, 19).replace('T', ' '),
success:true,
data: identityData
}
// This would return something like this:
// {
// timestamp: '2024-01-04 00:38:28',
// success: true,
// data: {
// success: true,
// uuid: '6595c84ce69d469f69ad39fb',
// token: 'eyJhbGciOiJ4UzI1NiJ9.eyJleHRlcm5hbFVzZXJJZCI6IjY1OTVjODRjZTY5ZDk2OWY2OWF33kMjlmYiIsInJvbGUiOiJBQ0NFU5MiLCJrZXlSZWYiOiI2MmZlNjQ3ZTJjODJlOTVhZDNhZTRjMzkiLCJleHAiOjE3MTIxOTExMDksImlhdCI6MTcwNDMyODcwOX0.fbhlcTQrp-h-spgxKU2J7wpEBN4I4iOYG5CBwuQKPLQ72',
// totalScore: 'OK',
// existingCustomer: false
// }
// }
// UUID: You can save the generated uuid of your user to link your user with our systems.
// Token: Is long lived and could be used to do calls in the name of the user if needed.
// Existing Customer: Will return true in case the user was already in the database, in such case we are returning the UUID of the already existing user.
res.status(200).send(response);
console.log(response);
} else {
response = {
timestamp: new Date().toISOString().slice(0, 19).replace('T', ' '),
success: false,
error: "Session didn't PASS, identity was not created"
}
res.status(200).send(response);
console.log(response)
}
} else {
// Process received data (for demonstration, just returning the received payload
// and include the timestamp)
response = {
timestamp: new Date().toISOString().slice(0, 19).replace('T', ' '),
success: true,
data: JSON.parse(webhookData.toString())
}
res.status(200).send(response);
// Write to a log so you can debug it.
console.log(response);
}
});
// Receives the information about a faceMatch attempt and verifies
// if it was correct and has not been tampered.
app.post('/auth', async (req, res) => {
const faceMatchData = JSON.parse(req.body.toString());
const {transactionId, token, interviewToken} = faceMatchData;
const verifyAttemptUrl = `${process.env.API_URL}/omni/authentication/verify`;
const params = { transactionId, token, interviewToken };
let verificationData={};
try{
verificationData = await doPost(verifyAttemptUrl, params, adminHeader);
} catch(e) {
console.log(e.message);
res.status(500).send({success:false, error: e.message});
return;
}
log = {
timestamp: new Date().toISOString().slice(0, 19).replace('T', ' '),
data: {...params,...verificationData}
}
res.status(200).send(verificationData);
// Write to a log so you can debug it.
console.log(log);
});
// Finishes the session started at /start
app.post('/finish', async (req, res) => {
let finishStatus = null;
const data = JSON.parse(req.body.toString());
const {token} = data;
if (!token) {
res.status(400).send({success:false, error:'Missing required parameter token'});
return;
}
header = {...defaultHeader};
header['X-Incode-Hardware-Id'] = token;
//Let's find out the score
const url = `${process.env.API_URL}/omni/finish-status`; let onboardingScore = null
try {
finishStatus = await doGet(url, {}, header);
} catch(e) {
console.log(e.message);
res.status(500).send({success:false, error: e.message});
return;
}
log = {
timestamp: new Date().toISOString().slice(0, 19).replace('T', ' '),
data: {finishStatus}
}
res.status(200).send(finishStatus);
// Write to a log so you can debug it.
console.log(log);
});
app.get('*', function(req, res){
res.status(404).json({error: `Cannot GET ${req.url}`});
});
app.post('*', function(req, res){
res.status(404).json({error: `Cannot POST ${req.url}`});
});
// Utility functions
const doPost = async (url, bodyparams, headers) => {
try {
const response = await fetch(url, { method: 'POST', body: JSON.stringify(bodyparams), headers});
if (!response.ok) {
//console.log(await response.json());
throw new Error('Request failed with code ' + response.status)
}
return response.json();
} catch(e) {
throw new Error('HTTP Post Error: ' + e.message)
}
}
const doGet = async (url, params, headers) => {
try {
const response = await fetch(`${url}?` + new URLSearchParams(params), {method: 'GET', headers});
if (!response.ok) {
//console.log(await response.json());
throw new Error('Request failed with code ' + response.status)
}
return response.json();
} catch(e) {
throw new Error('HTTP Get Error: ' + e.message)
}
}
/* Session Helper Functions
* For this example we simply save the session as json file in the /sessions folder
* in a real application you would save this information in a database.
**/
function writeSession(uniqueId, data){
const content = JSON.stringify(data, null, ' ');
try {
fs.writeFileSync(`sessions/${uniqueId}.json`, content);
} catch (err) {
console.error(err);
}
}
function readSession(uniqueId){
if(!isUUID(uniqueId) || !fs.existsSync(`sessions/${uniqueId}.json`)){
throw new Error('Invalid uniqueId');
}
const rawData = fs.readFileSync(`sessions/${uniqueId}.json`,{ encoding: 'utf8', flag: 'r' });
try {
return JSON.parse(rawData);
} catch(e){
throw new Error('Session data corrupted');
}
}
/* End Session Helper Functions **/
// Listen for HTTP
const httpPort = 3000;
app.listen(httpPort, () => {
console.log(`HTTP listening on: http://localhost:${httpPort}/`);
});
module.exports = app;