-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
377 lines (349 loc) · 11.6 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
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
// Set default require variables
var db = require('./server/db');
ObjectID = require('mongodb').ObjectID,
bodyParser = require('body-parser'),
cookieParser = require('cookie-parser'),
path = require('path'),
CASAuthentication = require('cas-authentication'),
session = require('express-session'),
express = require('express'),
app = express();
fs = require('fs'),
http = require('http'),
server = http.Server(app)
io = require('socket.io')(server),
MemoryStore = session.MemoryStore,
sessionStore = new MemoryStore(),
dbURI = 'mongodb://' + process.env.tmhtDBUser + ':' + process.env.tmhtDBPassword + '@ds023418.mlab.com:23418/tmht',
cookie = require('cookie');
var getIOInstance = function(){
return io;
}
// Set routes
var routes = require('./server/routes/index'),
rides = require('./server/routes/rides')(getIOInstance),
users = require('./server/routes/users');
// Set default variables
var port = process.env.PORT || 8005;
var cdta_api_stops = '?request=searchstops/';
var cdta_api_directions = '?request=directions/';
var cdta_api_sched = '?request=schedules/';
var cdta_api_status = '?request=alerts/';
var cdta_api_arrivals = '?request=arrivals/';
var cdta_api_key = process.env.cdta_api_key;
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', express.static(path.join(__dirname, '/')));
// Set up an Express session, which is required for CASAuthentication.
app.use(session({
secret: 'super secret key',
cookie: {
maxAge: 24 * 60 * 60 * 1000
},
resave: false,
saveUninitialized: false,
store: sessionStore
}));
// Create a new instance of CASAuthentication.
var cas = new CASAuthentication({
cas_url: 'https://cas-auth.rpi.edu/cas',
service_url: process.env.herokuurl || "http://localhost:" + port,
cas_version: '2.0'
});
app.use('/', routes);
app.use('/rides', rides);
app.use('/user', users);
// CAS route handlers
app.get('/login', cas.bounce, function (req, res) {
if (!req.session || !req.session.cas_user) {
res.redirect('/#/');
}
res.cookie('user', req.session.cas_user);
var collection = db.get().collection('users');
collection.find({rcs: req.session.cas_user}).toArray(function(err, docs){
if(err) throw err;
if(docs.length == 1){
res.redirect('/#/landing');
}
else{
// logic to notify user and tell them to sign up
res.redirect('/#/');
}
})
});
// Signup redirect with CAS
app.get('/signUp', cas.bounce, function(req,res){
if(!req.session || !req.session.cas_user) {
res.redirect('/#/');
}
var collection = db.get().collection('users');
collection.find({rcs: req.session.cas_user}).toArray(function(err, docs){
if(err) throw err;
if(docs.length > 0) {
res.cookie('user', req.session.cas_user);
//notify user that account alrady exists and log them in
res.redirect('/#/landing');
}
else {
res.redirect('/#/signUp');
}
})
});
// Logout redirect with CAS
app.get('/logout',function(req, res, next){
if(!req.session || !req.session.cas_user){
res.status(400).send('No user signed in');
}
else{
next();
}
}, cas.logout);
// Get CDTA stops
app.get('/cdta', function (req, resp) {
var search = req.query.search_b;
search= escape(search);
var x = '';
http.get({
host: 'api.cdta.org',
path: '/api/v1/' + cdta_api_stops + search + cdta_api_key
}, function (res) {
var pt= '/api/v1/' + cdta_api_stops + search + cdta_api_key;
res.on('data', function (d) {
x += d.toString();
});
res.on('end', function(){
resp.send(x);
});
});
});
// Get CDTA bus directions
app.get('/cdta_dir', function (req, resp) {
var search = req.query.search_b;
var x = '';
http.get({
host: 'api.cdta.org',
path: '/api/v1/' + cdta_api_directions + search + cdta_api_key
}, function (res) {
res.on('data', function (d) {
x += d.toString();
});
res.on('end', function(){
resp.send(x);
});
});
});
// Get CDTA bus directions
app.get('/cdta_dir', function (req, resp) {
var search = req.query.search_b;
var x = '';
http.get({
host: 'api.cdta.org',
path: '/api/v1/' + cdta_api_directions + search + cdta_api_key
}, function (res) {
res.on('data', function (d) {
x += d.toString();
});
res.on('end', function(){
resp.send(x);
});
});
});
// Get CDTA route
app.get('/get_route', function (req, resp) {
var x= '';
http.get({
host: 'api.cdta.org',
path: '/api/v1/' + cdta_api_sched + req.query.bus_num + '/weekday/' + req.query.info + cdta_api_key
}, function (res) {
res.on('data', function (d) {
x += d.toString();
});
res.on('end', function(){
resp.send(x);
});
});
});
// Get CDTA service status
app.get('/service_status', function (req, resp) {
var x= '';
http.get({
host: 'api.cdta.org',
path: '/api/v1/' + cdta_api_status + cdta_api_key
}, function (res) {
res.on('data', function (d) {
x += d.toString();
res.destroy();
return resp.send(x);
});
});
});
// Gets arrivals for stop
app.get('/stop_id', function (req, resp) {
var x= '';
http.get({
host: 'api.cdta.org',
path: '/api/v1/' + cdta_api_arrivals + req.query.stopid + '/2' + cdta_api_key
}, function (res) {
res.on('data', function (d) {
x += d.toString();
});
res.on('end', function(){
resp.send(x);
});
});
});
// Connect for variables
io.on("connection", function(socket){
var cookie_string = socket.request.headers.cookie;
if(session == undefined || typeof cookie_string == 'string'){
var parsed_cookies = cookie.parse(cookie_string);
var connect_sid = parsed_cookies['connect.sid'];
var decoded_id = cookieParser.signedCookie(connect_sid, 'super secret key')
socket.on('logged in', function(data){
if(decoded_id) {
sessionStore.get(decoded_id, function (error, session) {
if(session && session.cas_user){
socket.join(session.cas_user);
db.get().collection('users').find({rcs: session.cas_user}).toArray(function(err, results){
if(results[0] == undefined){
socket.emit('notifications', {
notifications: [],
count: 0
});
}
else{
if(results[0].notifications == undefined || results[0].notifications.length == 0){
socket.emit('notifications', {
notifications: [],
count: 0
});
}
else{
db.get().collection('users').aggregate([
{$unwind: '$notifications'},
{$match: {rcs: session.cas_user}},
{$sort: {"notifications.time": -1}},
{$group: {_id: '$_id', notifications: {$push: '$notifications'}}}
]).toArray(function(err, docs){
if(docs[0].notifications == undefined){
socket.emit('notifications', {
notifications: [],
count: 0
});
}
else{
db.get().collection('users').aggregate([
{$unwind : '$notifications'},
{$match: {'rcs': session.cas_user, 'notifications.seen': false}},
{$group: {
_id: '$_id',
notifications: {$push: '$notifications'},
}}
]).toArray(function(err, docs2){
if(err) throw err;
if(docs2[0] == undefined){
socket.emit('notifications', {
notifications: docs[0].notifications,
count: 0
});
}
else{
socket.emit('notifications', {
notifications: docs[0].notifications,
count: docs2[0].notifications.length
});
}
});
}
});
}
}
});
}
});
}
});
// Update notifications
socket.on('update notifications', function(data){
sessionStore.get(decoded_id, function(error, session){
db.get().collection('users').find({rcs: session.cas_user}).toArray(function(err, results){
if(results[0].notifications == undefined || results[0].notifications.length == 0){
socket.emit('notifications', {
notifications: [],
count: 0
});
}
else{
db.get().collection('users').aggregate([
{$unwind: '$notifications'},
{$match: {rcs: session.cas_user}},
{$sort: {"notifications.time": -1}},
{$group: {_id: '$_id', notifications: {$push: '$notifications'}}}
]).toArray(function(err, docs){
if(docs[0].notifications == undefined){
socket.emit('notifications', {
notifications: [],
count: 0
});
}
else{
db.get().collection('users').aggregate([
{$unwind : '$notifications'},
{$match: {'rcs': session.cas_user, 'notifications.seen': false}},
{$group: {
_id: '$_id',
notifications: {$push: '$notifications'},
}}
]).toArray(function(err, docs2){
if(err) throw err;
if(docs2[0] == undefined){
socket.emit('notifications', {
notifications: docs[0].notifications,
count: 0
});
}
else{
socket.emit('notifications', {
notifications: docs[0].notifications,
count: docs2[0].notifications.length
});
}
});
}
});
}
});
});
});
// When notifciations seen
socket.on('notifications seen', function(){
sessionStore.get(decoded_id, function(error, session){
if(error) throw error;
if(session == undefined){
}
else{
db.get().collection('users').find({rcs: session.cas_user}).forEach(function(doc){
doc.notifications.forEach(function(data){
db.get().collection('users').update({rcs:session.cas_user, notifications:data}, {$set: {'notifications.$.seen': true}}, function(err, results){
if(err) throw err;
});
});
});
}
})
});
}
});
// Connect to mongo
db.connect(dbURI, function(err) {
if (err) {
console.log('Unable to connect to Mongo.');
process.exit(1)
} else {
server.listen(port, function(){
console.log('Server running on port ' + port + '.');
})
}
});