-
Notifications
You must be signed in to change notification settings - Fork 6
/
index.js
2985 lines (2226 loc) · 72.7 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
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
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// TODO
// 429 handling throughout
// processing time per response in logs
// add integration (oauth) support to have user login
// setup env var
const fs = require('fs');
const envFile = __dirname + '/.env';
try {
if (fs.existsSync(envFile)) {
const env = require('node-env-file');
env(envFile);
}
} catch(err) {
console.log('Info: No .env file found. Assuming environment variables are already set.')
}
// check for env vars
if (!process.env.MONGO_URI) {
console.log('Error: Specify a mongo URI in environment as "MONGO_URI".');
process.exit(1);
}
if (!process.env.BASE_URL) {
console.log('Error: Specify the base URL for this bots shortened URLs in environment as "BASE_URL".');
process.exit(1);
}
if (!process.env.CISCOSPARK_ACCESS_TOKEN) {
console.log('Error: Specify a Webex Teams access token in environment as "CISCOSPARK_ACCESS_TOKEN".');
process.exit(1);
}
// TODO isn't used for anything yet
/*
var webAuth = "oauth";
if (
!process.env.WEBEXTEAMS_CLIENT_ID
|| !process.env.WEBEXTEAMS_CLIENT_SECRET
|| !process.env.WEBEXTEAMS_OAUTH_URL
) {
console.log('Warn: Specify "WEBEXTEAMS_CLIENT_ID", "WEBEXTEAMS_CLIENT_SECRET", and "WEBEXTEAMS_OAUTH_URL" in environment if you want use Webex Teams authentication.');
webAuth = "url";
}
*/
if (
!process.env.REVERSE_PROXY
|| process.env.REVERSE_PROXY.toLowerCase() != 'true'
)
console.log('Warn: Assuming app is not behind a reverse proxy. If it is, set "REVERSE_PROXY=true" in environment and add "X-Forwarded-Proto" to request header in the proxy.');
else
console.log('Warn: Make sure that your reverse proxy is set to rewrite the cookie path correctly.');
if (!process.env.WEBEXTEAMS_WEBHOOK_SECRET)
console.log('Warn: You really should be using a webhook secret. Specify a Webex Teams webhook secret in environment as "WEBEXTEAMS_WEBHOOK_SECRET".');
if (!process.env.WEBEXTEAMS_ADMIN_SPACE_ID)
console.log('Warn: Specify a Webex Teams Room/Space ID in environment as "WEBEXTEAMS_ADMIN_SPACE_ID" to receive errors in Webex Teams.');
if (!process.env.WEBEXTEAMS_SUPPORT_SPACE_ID)
console.log('Warn: Specify a Webex Teams Room/Space ID in environment as "WEBEXTEAMS_SUPPORT_SPACE_ID" to allow users to join the support space in Webex Teams.');
var sourceUrl = 'https://github.com/webex/eurl';
if (!process.env.SOURCE_URL)
console.log('Warn: You can set a source code url in environment as "SOURCE_URL". Using default source code url of '+sourceUrl);
else
sourceUrl = process.env.SUPPORT_EMAIL;
var permitDomains = [];
if (!process.env.PERMIT_DOMAINS)
console.log('Warn: If you want to limit supported domains, set PERMIT_DOMAINS in environment.');
else
permitDomains = process.env.PERMIT_DOMAINS.toLowerCase().split(/\ *,\ */);
var description = '';
if (!process.env.DESCRIPTION)
console.log('Warn: If you want a description used on the listing page and help message set DESCRIPTION in environment.');
else
description = process.env.DESCRIPTION;
console.log('heyo')
var supportEmail = '';
var supportUrl = '';
if (!process.env.SUPPORT_EMAIL){
if (!process.env.SUPPORT_URL){
console.log('Warn: You should have a support email or url set in environment as "SUPPORT_URL" so users can contact you.');
}else{
console.log('setting support url');
console.log(process.env.SUPPORT_URL);
console.log(process.env.SUPPORT_URL == '');
supportUrl = process.env.SUPPORT_URL;
}
}else{
console.log('setting support email');
supportEmail = process.env.SUPPORT_EMAIL;
}
if (!process.env.ADMIN_PORT)
console.log('Warn: Admin apis are disabled. Specify a TCP port to use in environment as "ADMIN_PORT" to enable them.');
else
console.log('Info: Admin apis are enabled on port '+process.env.ADMIN_PORT);
if (!process.env.PORT)
console.log('Warn: Specify a TCP port to use in environment as "PORT" or default port of 3000 will be used.');
const messagesPerSecond = process.env.WEBEXTEAMS_MESSAGES_PER_SECOND || 4;
if (!process.env.WEBEXTEAMS_MESSAGES_PER_SECOND)
console.log('Warn: Using default messages per second of '+messagesPerSecond+'. Specify "WEBEXTEAMS_MESSAGES_PER_SECOND" in environment.');
if (!process.env.LOG_FILE)
console.log('Warn: No log file set, so just using console. Set "LOG_FILE" in environment to log to a file.');
var logLevels = [ "error", "warn", "info", "verbose", "debug", "silly" ];
var logLevel = "info";
if (logLevels.includes(process.env.LOG_LEVEL))
logLevel = process.env.LOG_LEVEL;
console.log('Info: Setting log level to "'+logLevel+'". Set LOG_LEVEL in environment to "error", "warn", "info", "verbose", "debug", or "silly"');
// required packages
const assert = require('assert');
const winston = require('winston');
const expressWinston = require('express-winston');
const https = require('https');
const bodyParser = require('body-parser');
const path = require('path');
const ShortId = require('shortid');
const validator = require('validator');
const crypto = require('crypto');
const webexteams = require('ciscospark/env');
const qr = require('qr-image');
const mongoose = require('mongoose').connect(process.env.MONGO_URI);
const express = require('express');
const session = require('express-session');
const mongoDBStore = require('connect-mongodb-session')(session);
// setup logging
var logTransports = [];
var logConfig = winston.config;
var logStatusLevels = {
success: "debug",
warn: "debug",
error: "info"
}
var logOptions = {
level: logLevel,
timestamp: function() {
var now = new Date();
return now.getUTCFullYear() + "/" +
("0" + (now.getUTCMonth()+1)).slice(-2) + "/" +
("0" + now.getUTCDate()).slice(-2) + " " +
("0" + now.getUTCHours()).slice(-2) + ":" +
("0" + now.getUTCMinutes()).slice(-2) + ":" +
("0" + now.getUTCSeconds()).slice(-2);
},
formatter: function(options) {
return options.timestamp() + ' ' +
logConfig.colorize(options.level, options.level.toUpperCase()) + ' ' +
(options.message ? options.message : '') +
(options.meta && Object.keys(options.meta).length ? '\n\t'+ JSON.stringify(options.meta) : '' );
}
}
logTransports.push(new (winston.transports.Console)(logOptions));
// if log file is set add it to transports
if (process.env.LOG_FILE)
logTransports.push(new (winston.transports.File)(Object.assign(logOptions, { filename: process.env.LOG_FILE })));
// create logger
var log = new (winston.Logger)({
transports: logTransports
});
// status codes from memberships list that need to be handled differently or just ignored
var membershipsIgnoreStatusCode = [
404,
500
];
// cookie name for session id
const cookieSidName = 'sid';
// define db schema
const Publicspace = require('./models/publicspace');
// define express app
const app = express();
const router = express.Router();
// set tcp port for express
app.set('port', process.env.PORT || 3000);
// if behind a https -> http reverse proxy, must trust proxy
if (process.env.REVERSE_PROXY)
app.set('trust proxy', 1);
// create parsers for posts to shortid endpoint
const jsonParser = new bodyParser.json();
const textParser = new bodyParser.text({
type: '*/*'
});
// winston filter for sensitive data
var expressWinstonReqFilter = function (req, propName) {
if (propName == 'headers' && req[propName].cookie)
req[propName].cookie = req[propName].cookie.replace(RegExp('\('+cookieSidName+'=\)[^;]+'), '$1%REDACTED%');
return req[propName];
}
// express-winston logger makes sense BEFORE the router.
app.use(expressWinston.logger({
transports: logTransports,
statusLevels: logStatusLevels,
requestFilter: expressWinstonReqFilter
}));
// use the router
app.use(router);
// express-winston errorLogger makes sense AFTER the router.
app.use(expressWinston.errorLogger({
transports: logTransports,
statusLevels: logStatusLevels,
requestFilter: expressWinstonReqFilter
}));
// tell Express to serve files from our public folder
app.use(express.static(path.join(__dirname, 'public')))
// setup session store
var sessionStore = new mongoDBStore({
uri: process.env.MONGO_URI,
collection: 'sessions'
});
// handle errors for session store
sessionStore.on('error', function(error) {
assert.ifError(error);
assert.ok(false);
});
// create middleware for sessions
const sessionMiddleware = session({
store: sessionStore,
secret: crypto.createHash('sha256').update(process.env.CISCOSPARK_ACCESS_TOKEN).digest('base64'),
resave: false,
saveUninitialized: true,
name: cookieSidName,
cookie: {
secure: true,
httpOnly: false,
maxAge: 1000 * 60 * 60 * 1 // 1 hour
}
});
// apply session middleware
app.use(sessionMiddleware);
// if admin api enabled, setup admin express using same options as app express
if (process.env.ADMIN_PORT) {
const adminApp = express();
const adminRouter = express.Router();
adminApp.set('port', process.env.ADMIN_PORT);
if (process.env.REVERSE_PROXY)
adminApp.set('trust proxy', 1);
adminApp.use(expressWinston.logger({
transports: logTransports,
statusLevels: logStatusLevels,
requestFilter: expressWinstonReqFilter
}));
adminApp.use(router);
adminApp.use(expressWinston.errorLogger({
transports: logTransports,
statusLevels: logStatusLevels,
requestFilter: expressWinstonReqFilter
}));
// return jobs json
adminApp.get('/api/jobs/:type/:key/:data', function(req, res){
res.status(200).send(JSON.stringify(jobs[req.params.type][req.params.key][req.params.data]));
});
// return cache json
adminApp.get('/api/cache/:type/:key', function(req, res){
res.status(200).send(JSON.stringify(cache[req.params.type][req.params.key]));
});
// endpoint to check cache size from localhost only
adminApp.get('/api/cache/count', function(req, res){
var response = {
total: 0
};
Object.keys(cache).forEach(function(key){
response.total += Object.keys(cache[key]).length;
});
res.status(200).send(JSON.stringify(response));
});
// start admin express
var adminServer = adminApp.listen(adminApp.get('port'), function(){
log.info('Admin server listening on port '+adminServer.address().port);
});
}
// serve custom config for web app
app.get('/js/config.js', function(req, res){
res.setHeader("Content-type", "application/javascript");
res.charset = "UTF-8";
var javascriptConfig = `
var supportEmail = "`+supportEmail+`";
var supportUrl = "`+supportUrl+`";
var description = "`+description+`";
var botAvatar = "`+botDetails.avatar+`";
var botName = "`+botDetails.displayName+`";
var botEmail = "`+botDetails.emails[0]+`";
var botId = "`+botDetails.id+`";
`;
res.send(javascriptConfig);
});
// route to serve up the homepage (index.html)
app.get('/', function(req, res){
res.sendFile(path.join(__dirname, 'views/index.html'));
});
app.get('/alive', function(req, res){
res.status(200).send('OK');
});
// authenticate user link
app.get('/a/:tempPwd', function(req, res){
// must have tempPwd email and the tempPwd params must match
if (
req.session.tempPwd
&& req.session.email
&& req.session.tempPwd === req.params.tempPwd
) {
// users email
var email = req.session.email;
// remove the verify teams message to keep things clean. don't care about return
webexteams.messages.remove(req.session.authMessageId)
.then(function(){})
.catch(function(err){});
// create a new session
req.session.regenerate(function(err){
// lasts for 2 weeks
req.session.cookie.expires = new Date(Date.now() + (1000 * 60 * 60 * 24 * 14));
// set so we know if future requests are authenticated
req.session.authenticated = true;
// save the email
req.session.email = email;
// send them back to the listing
res.redirect(process.env.BASE_URL);
});
// missing something. maybe naughty
} else
// send them back to get email for verification
res.redirect(process.env.BASE_URL);
});
// reroute short ids that don't have leading #
app.get('/:shortId', function(req, res) {
res.redirect(process.env.BASE_URL+'#'+req.params.shortId);
});
// generate qr image for joining
var qrPath = '/img/qr/';
app.get(qrPath+':shortId', function(req, res){
var code = qr.image(process.env.BASE_URL+"#"+req.params.shortId, { type: 'png' });
res.setHeader('Content-type', 'image/png');
code.pipe(res);
});
// endpoint to get memberships cache for a user
app.get('/api/memberships', function(req, res){
// trying to get memberships outside of app
if (
!req.session.authenticated
|| !req.session.email
) {
res.status(401).send('Unauthorized');
return;
}
// if the cache exists for a user, return it
var memberships = {};
if (cache.memberships[req.session.email])
memberships = cache.memberships[req.session.email];
res.json({ responseCode: 0, memberships: memberships });
});
// endpoint to get spaces that are listed
app.get('/api/spaces', function(req, res){
// trying to get spaces but haven't authenticated yet
if (
!req.session.authenticated
|| !req.session.email
) {
// create a temp pwd
req.session.tempPwd = ShortId.generate();
//console.log('/api/spaces tempPwd created.');
//console.log(req.session);
// let web app know to display verification steps
res.json({
responseCode: -1,
});
// stop processing this route
return;
}
// get domain for user
var personDomain = getEmailDomain(req.session.email);
// search db for spaces that are listed
Publicspace.find({
"active": true,
"list": true,
$or: [
{ "internal": false },
{
$and: [
{ "internal": true },
{ "internalDomains": personDomain }
]
}
],
},
function (err, publicspaces){
// something failed
if (err) {
handleErr(err);
res.json({ responseCode: 1 });
// no spaces that have been enabled for listing
} else if (!publicspaces) {
res.json({ responseCode: 0, spaces: {} });
// things look good
} else {
// get only relevant data from the public spaces
parsedSpaces = publicspaces.map(function(publicspace){
// check if user is member of the space
var member = false;
if (
typeof(cache.memberships[req.session.email]) !== "undefined"
&& cache.memberships[req.session.email].includes(publicspace.shortId)
)
member = true;
// gather all necessary space data
return {
shortId: publicspace.shortId,
member: member,
created: publicspace.created,
updated: publicspace.updated,
internal: publicspace.internal,
title: publicspace.title,
hits: publicspace.hits
};
});
// return list
res.json({ responseCode: 0, spaces: parsedSpaces });
}
});
});
// authenticate user link
app.get('/api/auth/clean', function(req, res){
res.status(200).send();
if (req.session.authMessageId) {
webexteams.messages.remove(req.session.authMessageId)
.then(function(){})
.catch(function(err){});
}
});
// endpoint to validate email is valid
app.get('/api/auth/:email', function(req, res){
// get email from url
var email = req.params.email;
// check if domain is permitted
if (!isDomainPermitted(email)) {
log.info('email auth: domain not permitted: "'+email+'"');
res.json({ responseCode: 11 });
return;
}
// error if session doesn't have a temp password set
//console.log(req);
//console.log(req.session);
if (!req.session.tempPwd) {
log.error('email auth: no tempPwd set: "'+email+'"');
res.status(401).send('Unauthorized');
return;
}
// function to send validation message to user
var sendValidation = function() {
// save users email
req.session.email = email;
// send verification message to user in teams
var markdown = "A request to verify your identity was just made. If you didn't do that, please ignore this message. Open "+process.env.BASE_URL+"./a/"+req.session.tempPwd+" in the same browser to confirm your identity.";
webexteams.messages.create({
toPersonEmail: email,
markdown: markdown
})
// teams api call worked
.then(function(message) {
// if there's an existing verificaiton message, remove it
if (req.session.authMessageId) {
webexteams.messages.remove(req.session.authMessageId)
.then(function(){})
.catch(function(err){});
}
// set new verificaiton message id
req.session.authMessageId = message.id;
// return success to web app
res.json({ responseCode: 0 });
})
// failure from teams api
.catch(function(err){
// domain is dir sync'd and email is not teams enabled
if (err.body.message == "Failed to find user with specified email address.")
res.json({ responseCode: 12 });
// unknown error
else {
handleErr(err);
res.json({ responseCode: 11 });
}
});
}
// is it RFC compliant email?
if (!validator.isEmail(email)) {
// not valid email, error and return
log.error('email auth: invalid email: "'+email+'"');
res.json({ responseCode: 3 });
return;
}
// send validation message
else
sendValidation();
});
// endpoint to validate email is valid
app.get('/api/email/:email', function(req, res){
// get email from url
var email = req.params.email;
// check if domain is permitted
if (!isDomainPermitted(email)) {
log.info('email check: domain not permitted: "'+email+'"');
res.json({ responseCode: 3 });
return;
}
// is it RFC compliant email?
if (!validator.isEmail(email)) {
// not valid email, error and return
log.error('email check: invalid email: "'+email+'"');
res.json({ responseCode: 3 });
return;
}
// everything looks ok
res.json({ responseCode: 0 });
});
// endpoint to validate short id and get teams space details
app.get('/api/shortid/:shortId', function(req, res){
// shortId from url
var shortId = req.params.shortId;
// search db for short if provided
Publicspace.findOne({ 'shortId': shortId }, function (err, publicspace){
// something failed
if (err) {
handleErr(err);
res.json({ responseCode: 1 });
// not a valid short id
} else if (!publicspace) {
handleErr(shortId, false, "", 'invalid shortId');
res.json({ responseCode: 1 });
// space is not active
} else if (!publicspace.active) {
handleErr(shortId, false, "", 'no longer active shortId');
res.json({ responseCode: 2 });
// things look good
} else {
// get space details
webexteams.rooms.get(publicspace.spaceId)
.then(function(space) {
// found space
res.json({ responseCode: 0, title: space.title, logoUrl: publicspace.logoUrl, description: publicspace.description });
// update db with any differences in space details
if (
publicspace.title !== space.title
|| publicspace.isLocked !== space.isLocked
|| (
typeof(space.teamId) !== 'undefined'
&& publicspace.teamId !== space.teamId
)
|| (
typeof(space.teamId) === 'undefined'
&& publicspace.teamId !== ''
)
) {
// set title and isLocked in db
publicspace.title = space.title;
publicspace.isLocked = space.isLocked;
// set teamId in db
if (typeof(space.teamId) !== 'undefined')
publicspace.teamId = space.teamId;
// remove teamId from db
else
publicspace.teamId = '';
// silently update db
updatePublicSpace(publicspace, function(){
// do nothing
});
}
})
.catch(function(err){
// couldn't get space details
handleErr(err);
res.json({ responseCode: 11 });
});
}
});
});
// endpoint to add email to a space
app.post('/api/shortid/:shortId', jsonParser, function(req, res){
/*
possible response codes
0=added to space
2=email is not teams enabled
3=invlaid email
4=invlaid session
5=already in space
6=failed to add to space
7=general failure
*/
// short ID from url
var shortId = req.params.shortId;
// email from body
var email = req.body.email;
// check if domain is permitted
if (!isDomainPermitted(email)) {
log.info('add to space: domain not permitted: "'+email+'"');
res.json({ responseCode: 3 });
return;
}
// check for email
if (!email) {
log.error('add to space: missing email');
res.json({ responseCode: 3 });
return;
}
// valid email
if (!validator.isEmail(email)) {
log.error('add to space: invalid email: "'+email+'"');
res.json({ responseCode: 3 });
return;
}
// get db entry for shortid
Publicspace.findOneAndUpdate({ 'shortId': shortId }, { $inc: { hits: 1 }, $set: { 'updated': new Date() } }, { new: true }, function (err, publicspace) {
// failure to query db
if (err) {
handleErr(err);
res.json({ responseCode: 4 });
alertAdminSpace(req, 4, 'failed to call db; '+email+'; '+shortId, err);
}
// no valid space
else if (!publicspace) {
log.error('invalid shortId ', shortId);
res.json({ responseCode: 4 });
alertAdminSpace(req, 4, 'no entry in db; '+email+'; '+shortId, err);
}
// space is not active
else if (!publicspace.active) {
log.error('no longer active shortId ', shortId);
res.json({ responseCode: 10 });
}
// space is internal and user is not in domain
else if (
publicspace.internal
&& publicspace.internalDomains.indexOf(email.split('@')[1].toLowerCase()) === -1
) {
log.error(email+' not in internal space domains', publicspace.internalDomains);
res.json({ responseCode: 13 });
}
// things look good
else {
// space ID that user is trying to join
var spaceId = publicspace.spaceId;
// check if email is in space
webexteams.memberships.list({
roomId: spaceId,
personEmail: email
})
.then(function(memberships) {
// email is already in space
if (memberships.items.length === 1)
res.json({ responseCode: 5, spaceId: spaceId });
// email is not in space
else
addUser(spaceId, email);
})
.catch(function(err){
log.error("ERROR: Code=" + err.statusCode + "; Email=" + email + "; spaceId=" + spaceId);
if (membershipsIgnoreStatusCode.indexOf(err.statusCode) > -1)
addUser(spaceId, email);
else {
// check if its an existing teams user
webexteams.people.list({
email: email
})
.then(function(people){
// new teams user
if (people.items.length === 0)
addUser(spaceId, email);
// user exists
else {
res.json({ responseCode: 6 });
alertAdminSpace(req, 6, 'person exists, but couldnt add to space. bot might not be in space anymore; '+email+'; '+spaceId);
}
})
.catch(function(err){
handleErr(err);
res.json({ responseCode: 6 });
alertAdminSpace(req, 6, 'couldnt get person details; '+email+'; '+spaceId, err);
});
}
});
}
});
// put email in a space or request membership
function addUser(spaceId, email) {
// try to add user to space even though it could fail to avoid excessive API calls
webexteams.memberships.create({
roomId: spaceId,
personEmail: email
})
.then(function(membership) {
// was able to add user
log.info("added user to space", membership.id);
res.json({ responseCode: 0, spaceId: spaceId });
})
.catch(function(err){
// couldn't add user, but it might be ok. will check below
handleErr(err);
// domain is dir sync'd and email is not teams enabled
if (err.body.message.indexOf("not found") > -1) {
res.json({ responseCode: 12 });
return;
}
// get space details to determine if its currently locked
webexteams.rooms.get(spaceId)
.then(function(space){
// check to see if bot is a member of the space
webexteams.memberships.list({
roomId: spaceId,
personId: botDetails.id
})
.then(function(memberships){
// if the space is locked and the bot isn't a mod
if (
space.isLocked
&& !memberships.items[0].isModerator
) {
// message the space that the user is requesting access
webexteams.messages.create({
roomId: spaceId,
markdown: email+' would like to join this space'
})
.then(function(space) {
// sent message to space
res.json({ responseCode: 9 });
})
.catch(function(err){
// failed to send message to space
handleErr(err);
res.json({ responseCode: 6 });
alertAdminSpace(req, 6, 'couldnt send message to locked space to add user; '+email+'; '+spaceId, err);
});
}
// space isn't locked or its locked and bot is mod
// no good reason to not be able to add user
else {
res.json({ responseCode: 6 });
alertAdminSpace(req, 6, 'couldnt add user to space; '+email+'; '+spaceId, err);
}
})
.catch(function(err){
// couldn't get membership for bot. likely API services failure
handleErr(err);
res.json({ responseCode: 6 });
alertAdminSpace(req, 6, 'couldnt get bot membership details; '+email+'; '+spaceId, err);
});
})
.catch(function(err){
handleErr(err);
// very likely the bot isn't in the space
if (err.statusCode === 404) {
log.info("bot not in space", err);
alertAdminSpace(req, 6, 'bot not in space; '+email+'; '+spaceId, spaceId);
}
// couldn't get details on space. likely API service failure
else
alertAdminSpace(req, 6, 'couldnt get space details; '+email+'; '+spaceId, err);
res.json({ responseCode: 6 });
});
});
}
});
// validate webhook from teams cloud
app.post('/api/webhooks', textParser, function(req, res, next){
// immediately return 200 so webhook isn't disabled
res.status(200);
res.send('ok');
// make sure webhook isn't empty
if (req.body == '') {
log.error('invalid webhook: empty');
return;
}
// validate webhook hasn't been modified or faked
if (process.env.WEBEXTEAMS_WEBHOOK_SECRET) {
var hash = crypto.createHmac('sha1', process.env.WEBEXTEAMS_WEBHOOK_SECRET).update(req.body).digest('hex');
var teamsHash = req.get('X-Spark-Signature');
if (hash !== teamsHash) {
log.error('invalid webhook: wrong hash');
return;
}
}
// create objext from body of webhook
req.body = JSON.parse(req.body);
log.debug('webhook body: ', req.body);
// if webhook has status of disabled, ignore it
if (req.body.status == 'disabled') {
log.error('invalid webhook: status is disabled');
return;
}
// there was a change to membership to a space for a user other than the bot
if (
req.body.resource == 'memberships'
&& req.body.data.personId != botDetails.id
) {
// check if domain is permitted
if (!isDomainPermitted(req.body.data.personEmail)) {
log.info('invalid webhook: domain not permitted: "'+req.body.data.personEmail+'"');
return;
}
}
// if the event is a message to the bot and not created by the bot, get details
else if (
req.body.resource == 'messages'
&& req.body.event == 'created'
&& req.body.data.personId != botDetails.id
) {
// check if domain is permitted
if (!isDomainPermitted(req.body.data.personEmail)) {
log.info('invalid webhook: domain not permitted: "'+req.body.data.personEmail+'"');
return;
}