-
Notifications
You must be signed in to change notification settings - Fork 52
/
server.js
160 lines (142 loc) · 5.1 KB
/
server.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
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
const express = require("express");
const multer = require("multer");
const dotenv = require("dotenv");
dotenv.config({ path: ".env.local" });
const app = express();
const port = process.env.PORT || 3000;
app.use(express.urlencoded({ extended: false }));
app.use(express.json());
// We use multer to receive and process the verify image sent from the client for detectLivenessWithVerify
const storage = multer.memoryStorage();
const upload = multer({ storage: storage });
app.get("/", (_req, res) => {
res.sendFile(`${__dirname}/dist/face-angular-js/browser/index.html`);
});
// This is the server-side code example for generating access tokens of a liveness session without exposing API endpoint and key to the client-side.
// DISCLAIMER: In your production environment, you should perform this step on your app backend and pass down the session-authorization-token down to the frontend
// For more information on how to orchestrate the liveness solution, please refer to https://aka.ms/azure-ai-vision-face-liveness-tutorial
app.post(
"/api/generateAccessToken",
upload.single("VerifyImage"),
async (req, res) => {
let file = null;
const parameters = JSON.parse(req.body.Parameters);
const livenessOperationMode = parameters.livenessOperationMode;
const sendResultsToClient = parameters.sendResultsToClient;
const deviceCorrelationId = parameters.deviceCorrelationId;
const action = req.body.Action;
if (req.file) {
file = new Blob([req.file.buffer], { name: req.file.originalname });
}
if (file == undefined && action == "detectLivenessWithVerify") {
res.status(400).send({
message: "VerifyImage not provided for detectLivenessWithVerify",
token: null,
});
return;
}
// Ensure parameters are within expectation
if (!(action == "detectLiveness" || action == "detectLivenessWithVerify")) {
return res.status(400).send({
message: "action parameter not expected",
token: null,
});
}
if (
!(
livenessOperationMode == "Passive" ||
livenessOperationMode == "PassiveActive"
)
) {
return res.status(400).send({
message: "livenessOperationMode parameter not expected",
token: null,
});
}
if (typeof sendResultsToClient != "boolean") {
return res.status(400).send({
message: "sendResultsToClient parameter not expected",
token: null,
});
}
if (typeof deviceCorrelationId != "string") {
return res.status(400).send({
message: "deviceCorrelationId parameter not expected",
token: null,
});
}
// Note1: More information regarding each request parameter involved in creating a liveness session is here: https://aka.ms/face-api-reference-createlivenesssession
let formBody = JSON.stringify({
livenessOperationMode,
sendResultsToClient,
deviceCorrelationId,
});
// Note2: You can create a liveness session with verification by attaching a verify image during session-create, reference: https://aka.ms/face-api-reference-createlivenesswithverifysession
if (action == "detectLivenessWithVerify") {
formBody = new FormData();
formBody.append(
"Parameters",
JSON.stringify({
livenessOperationMode,
sendResultsToClient,
deviceCorrelationId,
})
);
formBody.append("VerifyImage", file, file.name);
}
// Token is fetched with API endpoint and key
// On server-side, the endpoint and key can be safely accessed without exposure to client-side
// detectLiveness takes a stringified JSON object and detectLivenessWithVerify takes a multipart form
const result = await fetchTokenOnServer(
process.env.FACE_ENDPOINT,
process.env.FACE_KEY,
action,
formBody
);
res.status(result.hasOwnProperty("error") ? 400 : 200).send(result);
return;
}
);
app.use(express.static(`${__dirname}/dist/face-angular-js/browser/`));
app.listen(port, () => {
console.log(`Server started at http://localhost:${port}`);
});
// Fetch Token Function
const fetchTokenOnServer = async (
faceApiEndPoint,
faceApiKey,
action,
formBody
) => {
try {
let headers = {
"Ocp-Apim-Subscription-Key": faceApiKey,
"X-MS-AZSDK-Telemetry": "sample=angular-face-web-sdk",
};
if (action === "detectLiveness") {
headers["Content-Type"] = "application/json";
}
const response = await fetch(
`${faceApiEndPoint}/face/v1.1-preview.1/${action}/singleModal/sessions`,
{
method: "POST",
headers: headers,
body: formBody,
}
);
const sessions = await response.json();
if (!response.ok) {
throw new Error(sessions.error?.message);
}
return { authToken: sessions.authToken, message: "success" };
} catch (error) {
if (typeof error === "string") {
return { error: { token: null, message: error } };
} else if (error instanceof Error) {
return {
error: { token: null, message: error.message ?? "Unknown error" },
};
}
return { error: { token: null, message: "Unknown error" } };
}
};