-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathZoomAPI.js
More file actions
557 lines (433 loc) · 16.2 KB
/
ZoomAPI.js
File metadata and controls
557 lines (433 loc) · 16.2 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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
// @flow
import { default as Axios } from 'axios'
import { URL } from 'url'
import { assign, get, pick, omit, isPlainObject, isArray, mapValues, once, lowerFirst, toLower, findKey } from 'lodash'
import Config from '../../server.config'
import logger from '../../../imports/logger'
import { IdScanResult, IdScanRequest } from '../processor/typings'
import {
ZoomAPIError,
failedEnrollmentMessage,
failedLivenessMessage,
failedMatchMessage,
enrollmentNotFoundMessage,
enrollmentAlreadyExistsMessage
} from '../utils/constants'
import { enrollmentIdFields, faceSnapshotFields, redactFieldsDuringLogging } from '../utils/logger'
import { substituteParams } from '../../utils/axios'
export class ZoomAPI {
http = null
defaultMinimalMatchLevel = null
defaultSearchIndexName = null
constructor(Config, httpFactory, logger) {
const { zoomMinimalMatchLevel, zoomSearchIndexName } = Config
const httpClientOptions = this._configureClient(Config, logger)
this.logger = logger
this.http = httpFactory(httpClientOptions)
this.defaultMinimalMatchLevel = Number(zoomMinimalMatchLevel)
this.defaultSearchIndexName = zoomSearchIndexName
this._configureRequests()
this._configureResponses()
}
async getLicenseKey(licenseType, customLogger = null) {
const response = await this.http.get('/license/:licenseType', {
customLogger,
params: { licenseType }
})
if (!get(response, 'key')) {
const exception = new Error('No license key in the FaceTec API response')
assign(exception, { response })
throw exception
}
return response
}
async getSessionToken(customLogger = null) {
const response = await this.http.get('/session-token', { customLogger })
if (!get(response, 'sessionToken')) {
const exception = new Error('No sessionToken in the FaceTec API response')
assign(exception, { response })
throw exception
}
return response
}
// eslint-disable-next-line require-await
async readEnrollment(enrollmentIdentifier, customLogger = null) {
return this._enrollmentRequest('get', enrollmentIdentifier, customLogger)
}
// eslint-disable-next-line require-await
async disposeEnrollment(enrollmentIdentifier, customLogger = null) {
return this._enrollmentRequest('delete', enrollmentIdentifier, customLogger)
}
async checkLiveness(payload, customLogger = null) {
let response
try {
response = await this._faceScanRequest('liveness', payload, null, customLogger)
} catch (exception) {
const { name, message } = exception
if (ZoomAPIError.SecurityCheckFailed === name) {
exception.message = failedLivenessMessage + ' because the ' + lowerFirst(message)
}
throw exception
}
return response
}
async submitEnrollment(enrollmentIdentifier, payload, customLogger = null) {
let response
const additionalData = { externalDatabaseRefID: enrollmentIdentifier }
try {
response = await this._faceScanRequest('enrollment', payload, additionalData, customLogger)
} catch (exception) {
let { name, message } = exception
const { NameCollision, SecurityCheckFailed } = ZoomAPIError
if (SecurityCheckFailed === name) {
message = failedEnrollmentMessage + ' because the ' + lowerFirst(message)
} else if (/enrollment\s+already\s+exists/i.test(message)) {
name = NameCollision
message = enrollmentAlreadyExistsMessage
}
assign(exception, { name, message })
throw exception
}
return response
}
async updateEnrollment(enrollmentIdentifier, payload, customLogger = null) {
let response
const additionalData = { externalDatabaseRefID: enrollmentIdentifier }
try {
response = await this._faceScanRequest('match-3d', payload, additionalData, customLogger)
} catch (exception) {
const { name, message } = exception
const { FacemapDoesNotMatch, SecurityCheckFailed } = ZoomAPIError
if ([FacemapDoesNotMatch, SecurityCheckFailed].includes(name)) {
exception.message = failedMatchMessage + ' because the ' + lowerFirst(message)
}
throw exception
}
return response
}
// eslint-disable-line require-await
async indexEnrollment(enrollmentIdentifier, indexName = null, customLogger = null) {
return this._3dDbRequest('enroll', enrollmentIdentifier, indexName, null, customLogger)
}
// eslint-disable-next-line require-await
async readEnrollmentIndex(enrollmentIdentifier, indexName = null, customLogger = null) {
return this._3dDbIndexRequest('get', enrollmentIdentifier, indexName, customLogger)
}
// eslint-disable-next-line require-await
async removeEnrollmentFromIndex(enrollmentIdentifier, indexName = null, customLogger = null) {
return this._3dDbIndexRequest('delete', enrollmentIdentifier, indexName, customLogger)
}
async faceSearch(enrollmentIdentifier, minimalMatchLevel: number = null, indexName = null, customLogger = null) {
let minMatchLevel = minimalMatchLevel
let response
if (null === minMatchLevel) {
minMatchLevel = this.defaultMinimalMatchLevel
}
try {
response = await this._3dDbRequest('search', enrollmentIdentifier, indexName, { minMatchLevel }, customLogger)
} catch (exception) {
// checking is the reason of error is index wasn't initialized yet
// that means there just no enrollment were added
// for some other kind of reason re-throwing an exception
if (!/groupName\s+does\s+not\s+exist/i.test(exception.message)) {
throw exception
}
// if it's because empty, non-initialized index - will
// ignore the error an return empty results
response = {
success: true,
error: false,
results: []
}
}
return response
}
async idscan(enrollmentIdentifier, payload: IdScanRequest, customLogger = null): Promise<IdScanResult> {
const { idScan, idScanFrontImage, idScanBackImage } = payload
const payloadData = {
externalDatabaseRefID: enrollmentIdentifier,
idScan,
idScanFrontImage,
idScanBackImage,
minMatchLevel: this.defaultMinimalMatchLevel
}
return this.http.post(`/match-3d-2d-idscan`, payloadData, { customLogger })
}
async liveness2d(image, customLogger = null) {
const payload = { image }
let response
try {
response = await this.http.post(`/liveness-2d`, payload, { customLogger })
} catch (exception) {
this._logUnexpectedExecption(exception)
throw exception
}
const { success, isLikelyRealPerson } = response
if (!success || !isLikelyRealPerson) {
const exception = new Error(failedLivenessMessage)
assign(exception, { response, name: ZoomAPIError.LivenessCheckFailed })
throw exception
}
return response
}
async match3d2dFacePortrait(image, externalDatabaseRefID, minMatchLevel = null, customLogger = null) {
const minMatch = null === minMatchLevel ? this.defaultMinimalMatchLevel : minMatchLevel
const payload = {
image,
externalDatabaseRefID,
minMatchLevel: minMatch
}
let response
try {
response = await this.http.post(`/match-3d-2d-face-portrait`, payload, { customLogger })
} catch (exception) {
this._logUnexpectedExecption(exception)
throw exception
}
// normalize response checks: require processed and sufficient matchLevel
const { success, matchLevel, imageProcessingStatusEnumInt } = response
if (!success || imageProcessingStatusEnumInt !== 0 || Number(matchLevel) < Number(minMatch)) {
const exception = new Error(failedMatchMessage)
assign(exception, { response, name: ZoomAPIError.FacemapDoesNotMatch })
throw exception
}
return response
}
_configureClient(Config, logger) {
const { zoomLicenseKey, zoomServerBaseUrl } = Config
const serverURL = new URL(zoomServerBaseUrl)
const { username, password } = serverURL
let httpClientOptions = {
headers: {
'X-Requested-With': 'XMLHttpRequest',
'Content-Type': 'application/json',
'X-Device-Key': zoomLicenseKey
}
}
// passing basic auth via url isn't recommended
// so we're removing them from the url string
// and passing via Authorization headers
if (username || password) {
httpClientOptions = {
...httpClientOptions,
auth: { username, password }
}
serverURL.username = ''
serverURL.password = ''
}
httpClientOptions = {
...httpClientOptions,
baseURL: serverURL.toString()
}
logger.debug('Initialized Zoom API client with the options:', httpClientOptions)
return httpClientOptions
}
_configureRequests() {
const { request } = this.http.interceptors
request.use(request => {
const rawRequest = substituteParams(
request,
(parameter, value) => (enrollmentIdFields.includes(parameter) ? toLower(value) : value) || ''
)
this._logRequest(request)
return isPlainObject(request.data) ? this._configurePayload(rawRequest) : rawRequest
})
}
_configurePayload(request) {
const { data } = request
const identifierKey = findKey(data, (_, key) => enrollmentIdFields.includes(key))
if (!identifierKey) {
return request
}
const identifier = data[identifierKey]
return {
...request,
data: {
...data,
[identifierKey]: toLower(identifier)
}
}
}
_configureResponses() {
const { response } = this.http.interceptors
response.use(
async response => this._responseInterceptor(response),
async exception => this._exceptionInterceptor(exception)
)
}
async _responseInterceptor(response) {
const zoomResponse = this._transformResponse(response)
const { error, errorMessage } = zoomResponse
this._logResponse('Received response from Zoom API:', response)
if (true === error) {
const exception = new Error(errorMessage || 'FaceTec API response is empty')
exception.response = zoomResponse
throw exception
}
return zoomResponse
}
async _exceptionInterceptor(exception) {
const { response, message } = exception
if (response && isPlainObject(response.data)) {
this._logResponse('Zoom API exception:', response)
const zoomResponse = this._transformResponse(response)
const { errorMessage: zoomMessage } = zoomResponse
exception.message = zoomMessage || message
exception.response = zoomResponse
} else {
this._logUnexpectedExecption(exception)
delete exception.response
}
throw exception
}
_transformResponse(response) {
return get(response, 'data', {})
}
_logRequest(request) {
const requestCopy = pick(request, 'url', 'method', 'headers', 'params')
const { data, customLogger } = request
const logger = customLogger || this.logger
requestCopy.data = this._createLoggingSafeCopy(data)
logger.trace('Calling Zoom API:', requestCopy)
}
_logResponse(logMessage, response) {
const { data, config } = response
const logger = config?.customLogger || this.logger
logger.debug(logMessage, this._createLoggingSafeCopy(data))
}
_logUnexpectedExecption(exception) {
const { logger } = this
const { response, message } = exception
if (response) {
const { data, status, statusText, config } = response
const log = config?.customLogger || logger
exception.name = ZoomAPIError.HttpException
log.debug('HTTP exception during Zoom API call:', { data, status, statusText })
} else {
exception.name = ZoomAPIError.UnexpectedException
logger.debug('Unexpected exception during Zoom API call:', message)
}
}
_getDatabaseIndex(indexName = null) {
let databaseIndex = indexName
if (null === indexName) {
databaseIndex = this.defaultSearchIndexName
}
return databaseIndex
}
async _enrollmentRequest(operation, enrollmentIdentifier, customLogger = null) {
let response
try {
response = await this.http[operation]('/enrollment-3d/:enrollmentIdentifier', {
customLogger,
params: { enrollmentIdentifier: enrollmentIdentifier.toLowerCase() }
})
} catch (exception) {
const { message } = exception
if (/(no\s+entry\s+found|no\s+records\s+were)/i.test(message)) {
assign(exception, {
name: ZoomAPIError.FacemapNotFound,
message: enrollmentNotFoundMessage
})
}
throw exception
}
return response
}
async _faceScanRequest(operation, payload, additionalData = null, customLogger = null) {
const payloadData = {
...pick(payload, faceSnapshotFields),
...(additionalData || {})
}
const response = await this.http.post(`/${operation}-3d`, payloadData, { customLogger })
const { LivenessCheckFailed, SecurityCheckFailed, FacemapDoesNotMatch } = ZoomAPIError
const { success, faceScanSecurityChecks, matchLevel } = response
const {
faceScanLivenessCheckSucceeded,
auditTrailVerificationCheckSucceeded,
replayCheckSucceeded,
sessionTokenCheckSucceeded
} = faceScanSecurityChecks
if (!success) {
let isFaceMapDoesntMatch = false
let message = `Unknown exception happened during ${operation} request`
if (!sessionTokenCheckSucceeded) {
message = 'Session token is missing or was failed to be checked'
} else if (!replayCheckSucceeded) {
message = 'Replay check was failed'
} else if (!faceScanLivenessCheckSucceeded) {
message = failedLivenessMessage
if (!auditTrailVerificationCheckSucceeded) {
message += ' because the photoshoots evaluated to be of poor quality'
}
} else if (auditTrailVerificationCheckSucceeded) {
// if all security checks have been passed - check for the match level
isFaceMapDoesntMatch = 'matchLevel' in response && Number(matchLevel) < 10
if (isFaceMapDoesntMatch) {
message = "Face map you're trying to enroll doesn't match the already enrolled one"
}
}
const exception = new Error(message)
let { name } = exception
if (!sessionTokenCheckSucceeded || !replayCheckSucceeded) {
name = SecurityCheckFailed
} else if (!faceScanLivenessCheckSucceeded) {
name = LivenessCheckFailed
} else if (isFaceMapDoesntMatch) {
name = FacemapDoesNotMatch
}
assign(exception, { name, response })
throw exception
}
return response
}
async _3dDbRequest(operation, enrollmentIdentifier, indexName = null, additionalData = null, customLogger = null) {
let response
const databaseIndex = this._getDatabaseIndex(indexName)
const payload = {
externalDatabaseRefID: enrollmentIdentifier,
groupName: databaseIndex,
...(additionalData || {})
}
try {
response = await this.http.post(`/3d-db/${operation}`, payload, { customLogger })
} catch (exception) {
const { message } = exception
if (/enrollment\s+does\s+not\s+exist/i.test(message)) {
assign(exception, {
message: enrollmentNotFoundMessage,
name: ZoomAPIError.FacemapNotFound
})
}
throw exception
}
return response
}
async _3dDbIndexRequest(method, enrollmentIdentifier, indexName = null, customLogger = null) {
const databaseIndex = this._getDatabaseIndex(indexName)
const payload = {
identifier: enrollmentIdentifier,
groupName: databaseIndex
}
const response = await this.http.post(`/3d-db/${method}`, payload, { customLogger })
const { success } = response
if (false === success) {
const exception = new Error(enrollmentNotFoundMessage)
assign(exception, { response, name: ZoomAPIError.FacemapNotFound })
throw exception
}
return response
}
_createLoggingSafeCopy(payload) {
if (isArray(payload)) {
return payload.map(item => this._createLoggingSafeCopy(item))
}
if (!isPlainObject(payload)) {
return payload
}
return mapValues(omit(payload, redactFieldsDuringLogging), payloadField =>
this._createLoggingSafeCopy(payloadField)
)
}
}
export default once(() => new ZoomAPI(Config, Axios.create, logger.child({ from: 'ZoomAPI' })))