forked from TwilioDevEd/ipm-quickstart-node
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
65 lines (56 loc) · 1.95 KB
/
index.js
File metadata and controls
65 lines (56 loc) · 1.95 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
/*
Load Twilio configuration from .env config file - the following environment
variables should be set:
process.env.TWILIO_ACCOUNT_SID
process.env.TWILIO_API_KEY
process.env.TWILIO_API_SECRET
process.env.TWILIO_IPM_SERVICE_SID
*/
require('dotenv').load();
var http = require('http');
var path = require('path');
var AccessToken = require('twilio').AccessToken;
var IpMessagingGrant = AccessToken.IpMessagingGrant;
var express = require('express');
var randomUsername = require('./randos');
// Create Express webapp
var app = express();
app.use(express.static(path.join(__dirname, 'public')));
/*
Generate an Access Token for a chat application user - it generates a random
username for the client requesting a token, and takes a device ID as a query
parameter.
*/
app.get('/token', function(request, response) {
var appName = 'TwilioChatDemo';
var identity = randomUsername();
var deviceId = request.query.device;
// Create a unique ID for the client on their current device
var endpointId = appName + ':' + identity + ':' + deviceId;
// Create a "grant" which enables a client to use IPM as a given user,
// on a given device
var ipmGrant = new IpMessagingGrant({
serviceSid: process.env.TWILIO_IPM_SERVICE_SID,
endpointId: endpointId
});
// Create an access token which we will sign and return to the client,
// containing the grant we just created
var token = new AccessToken(
process.env.TWILIO_ACCOUNT_SID,
process.env.TWILIO_API_KEY,
process.env.TWILIO_API_SECRET
);
token.addGrant(ipmGrant);
token.identity = identity;
// Serialize the token to a JWT string and include it in a JSON response
response.send({
identity: identity,
token: token.toJwt()
});
});
// Create http server and run it
var server = http.createServer(app);
var port = process.env.PORT || 3000;
server.listen(port, function() {
console.log('Express server running on *:' + port);
});