-
Notifications
You must be signed in to change notification settings - Fork 227
/
server.js
114 lines (102 loc) · 3.51 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
require('dotenv').config();
const crypto = require('crypto');
const express = require("express");
const path = require("path");
const jwt = require("jsonwebtoken");
const fetch = require('node-fetch');
const cookieParser = require('cookie-parser');
const WEBCHAT_SECRET = process.env.WEBCHAT_SECRET;
const DIRECTLINE_ENDPOINT_URI = process.env.DIRECTLINE_ENDPOINT_URI;
const APP_SECRET = process.env.APP_SECRET;
const directLineTokenEp = `https://${DIRECTLINE_ENDPOINT_URI || "directline.botframework.com"}/v3/directline/tokens/generate`;
// Initialize the web app instance,
const app = express();
app.use(cookieParser());
let options = {};
// uncomment the line below if you wish to allow only specific domains to embed this page as a frame
//options = {setHeaders: (res, path, stat) => {res.set('Content-Security-Policy', 'frame-ancestors example.com')}};
// Indicate which directory static resources
// (e.g. stylesheets) should be served from.
app.use(express.static(path.join(__dirname, "public"), options));
// begin listening for requests.
const port = process.env.PORT || 8080;
const region = process.env.REGION || "Unknown";
app.listen(port, function() {
console.log("Express server listening on port " + port);
});
function isUserAuthenticated(){
// add here the logic to verify the user is authenticated
return true;
}
const appConfig = {
isHealthy : false,
options : {
method: 'POST',
headers: {
'Authorization': 'Bearer ' + WEBCHAT_SECRET
}
}
};
function healthResponse(res, statusCode, message) {
res.status(statusCode).send({
health: message,
region: region
});
}
function healthy(res) {
healthResponse(res, 200, "Ok");
}
function unhealthy(res) {
healthResponse(res, 503, "Unhealthy");
}
app.get('/health', async function(req, res){
if (!appConfig.isHealthy) {
try {
const fetchResponse = await fetch(directLineTokenEp, appConfig.options);
const parsedBody = await fetchResponse.json();
appConfig.isHealthy = true;
healthy(res);
}
catch (err) {
unhealthy(res);
}
}
else {
healthy(res);
}
});
app.post('/chatBot', async function(req, res) {
if (!isUserAuthenticated()) {
res.status(403).send();
return;
}
try {
const fetchResponse = await fetch(directLineTokenEp, appConfig.options);
const parsedBody = await fetchResponse.json();
var userid = req.query.userId || req.cookies.userid;
if (!userid) {
userid = crypto.randomBytes(4).toString('hex');
res.cookie("userid", userid, { sameSite: "none", secure: true, httpOnly: true, expires: new Date(new Date().setFullYear(new Date().getFullYear() + 1)) });
}
var response = {};
response['userId'] = userid;
response['userName'] = req.query.userName;
response['locale'] = req.query.locale;
response['connectorToken'] = parsedBody.token;
/*
//Add any additional attributes
response['optionalAttributes'] = {age: 33};
*/
if (req.query.lat && req.query.long) {
response['location'] = {lat: req.query.lat, long: req.query.long};
}
response['directLineURI'] = DIRECTLINE_ENDPOINT_URI;
const jwtToken = jwt.sign(response, APP_SECRET);
res.send(jwtToken);
}
catch (err) {
appConfig.isHealthy = false;
res.status(err.statusCode).send();
console.log("failed");
}
});