-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
65 lines (61 loc) · 2.14 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
const crypto = require('crypto');
const express = require("express");
const path = require("path");
const jwt = require("jsonwebtoken");
const rp = require("request-promise");
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;
// Initialize the web app instance,
const app = express();
app.use(cookieParser());
// Indicate which directory static resources
// (e.g. stylesheets) should be served from.
app.use(express.static(path.join(__dirname, "public")));
// begin listening for requests.
const port = process.env.PORT || 3000;
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;
}
app.post('/chatBot', function(req, res) {
if (!isUserAuthenticated()) {
res.status(403).send();
return
}
const options = {
method: 'POST',
uri: 'https://directline.botframework.com/v3/directline/tokens/generate',
headers: {
'Authorization': 'Bearer ' + WEBCHAT_SECRET
},
json: true
};
rp(options)
.then(function (parsedBody) {
var userid = req.query.userId || req.cookies.userid;
if (!userid) {
userid = crypto.randomBytes(4).toString('hex');
res.cookie("userid", userid);
}
var response = {};
response['userId'] = userid;
response['userName'] = req.query.userName;
response['connectorToken'] = parsedBody.token;
response['optionalAttributes'] = {age: 33};
if (req.query.region) {
response['region'] = req.query.region;
}
response['directLineURI'] = DIRECTLINE_ENDPOINT_URI;
const jwtToken = jwt.sign(response, APP_SECRET);
res.send(jwtToken);
})
.catch(function (err) {
res.status(err.statusCode).send();
console.log("failed");
});
});