forked from skuusk/sync-quickstart-node
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
executable file
·57 lines (49 loc) · 1.62 KB
/
index.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
'use strict';
const http = require('http');
const path = require('path');
const express = require('express');
const AccessToken = require('twilio').jwt.AccessToken;
const SyncGrant = AccessToken.SyncGrant;
const randomUsername = require('./randos');
const config = require('./config.js');
// Create Express webapp
var app = express();
app.use(express.static(path.join(__dirname, 'public')));
/*
Generate an Access Token for a sync 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', (request, response) => {
let appName = 'TwilioSyncDemo';
let identity = randomUsername();
let deviceId = request.query.device;
// Create a unique ID for the client on their current device
let endpointId = `${appName}:${identity}:${deviceId}`;
// Create a "grant" which enables a client to use Sync as a given user,
// on a given device
let syncGrant = new SyncGrant({
serviceSid: config.serviceSid,
endpointId: endpointId
});
// Create an access token which we will sign and return to the client,
// containing the grant we just created
let token = new AccessToken(
config.accountSid,
config.apiKey,
config.apiSecret
);
token.addGrant(syncGrant);
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, () => {
console.log('Express server running on *:' + port);
});