This repository was archived by the owner on Sep 19, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
749 lines (627 loc) · 25.1 KB
/
app.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
/**
* Module dependencies.
*/
var express = require('express'),
fs = require('fs'),
OAuth2 = require("oauth").OAuth2,
Url = require('url'),
querystring = require('querystring'),
GitHubApi = require("github").GitHubApi,
check = require('validator').check,
DataStoreHandler = require('./dataStoreHandler'),
spawn = require('child_process').spawn,
sanitize = require('validator').sanitize;
//Some global vars
var redisConnected = true;
//Default port number
var portNumber = 8080;
var config_directory = "/config";
var config_filename = "hackathon-config.json";
/*
I know this is env non-specific at the moment .. should change later
*/
try {
config = JSON.parse(fs.readFileSync(config_directory + '/' + config_filename, 'ascii'));
} catch(e) {
throw new Error('Config file is formatted incorrectly or not found: ' + config_directory + '/' + config_filename + ". " + e.toString());
}
var app = module.exports = express.createServer();
var current_root_host = config.rootHost;
// Redis store setup for sessions
var RedisStore = require('connect-redis')(express);
var store = new RedisStore;
store.client.on("error", redisError);
store.client.on("connect", redisConnect);
function redisConnect() {
if(!redisConnected) {
redisConnected = true;
console.log("Redis Session store connected; applying session.");
}
}
function redisError(error) {
console.log("Redis Session store failed: " + error);
}
// Mongoose (Mongo) stuff
// Configuration
app.configure(function(){
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser());
app.use(express.session({ "secret": config.sessionSecret, "store": store, "maxAge" : 1800000 }));
app.use(express.compiler({ src: __dirname + '/public', enable: ['less'] }));
app.use(app.router);
app.use(express.static(__dirname + '/public'));
});
app.configure('development', function(){
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});
app.configure('production', function(){
app.use(express.errorHandler());
portNumber = 80;
});
// Routes
app.get('/', maintenanceMiddleware, function(req, res){
res.render('index', {
devMode: this.config.devMode,
title: 'Hack4Reno',
sectionTitle: 'Hack4Reno Hackathoner Hub'
});
});
app.get('/maintenance', function(req, res) {
res.render('maintenance', {
title: 'Hack4Reno',
sectionTitle: 'Maintenance'
});
});
app.get('/logout', function(req, res) {
if(req.session) {
req.session.githubAccessToken = null;
req.session.destroy();
}
res.redirect("/");
});
app.get('/participant-signup', function(req, res){
res.render('signup', {
title: 'Hack4Reno',
sectionTitle: 'Participant Registration'
});
});
app.get('/participant-join-submitted', function(req, res){
res.render('signupRequestJoinTeam', {
title: 'Hack4Reno',
sectionTitle: ''
});
});
//This is the callback from github
app.get('/participant-signup-validated', requireUserMiddleWare, function(req, res, next){
var Participant = app.mongo.model('Participant');
Participant.find({username: req.session.user.login}, function(err, docs) {
if(err) {
next(err);
} else {
if(docs !== undefined && docs != null && docs.length == 1) {
//If the user exists, update the oAuthAccessCode in the db and continue
var currentParticipant = docs[0];
var currentParticipantId = currentParticipant._id;
currentParticipant.oAuthAccessCode = req.session.githubAccessToken;
currentParticipant.lastLogin = req.session.lastLogin;
currentParticipant.save(function(err) {
if(err) {
next(err);
} else {
saveInfoToSession(req, {userId: currentParticipantId});
res.redirect('/main');
}
});
} else {
var newParticipant = new Participant({gravatarId: req.session.user.gravatar_id, username: req.session.user.login, oAuthAccessCode: req.session.githubAccessToken});
newParticipant.save(function(err) {
if(err) {
console.log("Err=" + err);
next(err);
} else {
saveInfoToSession(req, {userId: newParticipant._id});
res.redirect('/main');
}
});
}
}
});
/*//Check if user is registered
var Participant = app.mongo.model('Participant');
Participant.find({username: req.session.user.login}, function(err, docs) {
if(err) {
next(err);
} else {
if(docs !== undefined && docs != null && docs.length == 1) {
//If the user exists, update the oAuthAccessCode in the db and continue
var currentParticipant = docs[0];
var currentParticipantId = currentParticipant._id;
currentParticipant.oAuthAccessCode = req.session.githubAccessToken;
currentParticipant.save(function(err) {
if(err) {
next(err);
} else {
//Look to see if the user is a participant. If not, send them to join a team.
var Team = app.mongo.model('Team');
//TODO: Look into $or clause for mongoose
Team.where('participants').in([currentParticipantId]).run(function(err, docs) {
if(err) {
console.log("Err=" + err);
next(err);
} else {
if(docs !== undefined && docs != null && docs.length > 0) {
saveInfoToSession(req, {userId: currentParticipantId, teams: docs, teamId: docs[0]._id, teamName: docs[0].name, hasTeam: true});
res.redirect("/main");
} else {
//Ok, user is not a participant, but maybe they are a pending participant
Team.where('pendingParticipants').in([currentParticipantId]).run(function(err, docs) {
if(err) {
console.log("Err=" + err);
} else {
if(docs !== undefined && docs != null && docs.length > 0) {
saveInfoToSession(req, {userId: currentParticipantId, pendingTeams: docs, pendingTeam: true});
res.redirect("/main");
} else {
saveInfoToSession(req, {userId: currentParticipantId, teamId: null, teamName: "", hasTeam: false, pendingTeam: false});
res.redirect('/participant-signup-validated-join-team');
}
}
});
}
}
});
}
});
} else {
//Setup user
var newParticipant = new Participant({gravatarId: req.session.user.gravatar_id, username: req.session.user.login, oAuthAccessCode: req.session.githubAccessToken});
newParticipant.save(function(err) {
if(err) {
console.log("Err=" + err);
next(err);
} else {
saveInfoToSession(req, {userId: newParticipant._id});
res.redirect('/participant-signup-validated-join-team');
}
});
}
}
});*/
});
//OVERLORD FUNCTIONS START
app.get('/overlord-setup', function(req, res, next) {
if(!config.overlordSetup) {
res.render('overlordSetupHelp', {
title: 'Hack4Reno',
sectionTitle: 'Overlord Setup'
});
} else {
res.redirect('/');
}
});
app.get('/overlord-setup-validated', function(req, res, next) {
if(!config.overlordSetup) {
res.render('overlordSetupDone', {
title: 'Hack4Reno',
sectionTitle: 'Overlord Setup',
code: req.session.oAuthAccessCode,
token: req.session.githubAccessToken
});
} else {
res.redirect('/');
}
});
app.post('/overlord-oauth', function(req, res, next) {
if(!config.overlordSetup) {
// OAuth setup
var oauth = new OAuth2(config.githubClientId, config.githubSecretId, 'https://github.com/', 'login/oauth/authorize', 'login/oauth/access_token');
var authorizeURL = oauth.getAuthorizeUrl({
redirect_uri: current_root_host + 'github-callback',
scope: "repo"
});
res.redirect(authorizeURL);
} else {
res.redirect('/');
}
});
// OVERLORD FUNCTIONS END
app.get('/participant-signup-validated-join-team', requireUserMiddleWare, function(req, res, next) {
var Team = app.mongo.model('Team');
Team.$where('this.needsDevelopers === true || this.needsDesigners === true || this.needsIdeas === true').populate('participants').exec(function(err, docs) {
if(err) {
next(err);
} else {
res.render('signupStep2', {
title: 'Hack4Reno',
sectionTitle: 'Participant Registration',
userName: req.session.user.login,
gravatarURL: getGravatarURL(req),
needsTeams: docs,
organizationName: config.organizationName,
newTeam: new Team(),
loggedIn: true
});
}
});
});
function execOAuthForCommand(callback) {
var oauth = new OAuth2(config.githubClientId, config.githubSecretId, 'https://github.com/', 'login/oauth/authorize', 'login/oauth/access_token');
oauth.getOAuthAccessToken(config.overlordOAuthCode, {}, function (err, access_token, refresh_token) {
if(err) {
console.log("OAuthError:: " + err);
callback(err, null);
} else {
console.log("OAuthSuccess:: " + access_token + ", refresh_token:" + refresh_token);
callback(null, access_token);
}
});
}
app.get('/github-callback', function(req, res, next) {
console.log("GET called");
var url = Url.parse(req.url);
var query = querystring.parse(url.query);
// OAuth setup
var oauth = new OAuth2(config.githubClientId, config.githubSecretId, 'https://github.com/', 'login/oauth/authorize', 'login/oauth/access_token');
var accessCode = query.code;
oauth.getOAuthAccessToken(query.code, {}, function (err, access_token, refresh_token) {
if (err) {
console.log("Err=" + JSON.stringify(err));
next(err);
return;
}
var accessToken = access_token;
var refreshToken = refresh_token;
console.log("access_token=" + accessToken);
console.log("refresh_token=" + refreshToken);
//Let's try using our new found access_token
var github = new GitHubApi(true);
github.authenticateOAuth(accessToken);
var user = github.getUserApi();
user.show(function(err, user) {
if (err) {
console.log("Err=" + JSON.stringify(err));
next(err);
} else {
console.log("user=" + JSON.stringify(user));
//Ok, we got an access code, it's valid, and we got a user back.
req.session.githubAccessToken = accessToken;
req.session.oAuthAccessCode = accessCode;
req.session.loggedIn = true;
req.session.user = user;
saveInfoToSession(req, {login: req.session.user.login});
if(!config.overlordSetup) {
res.redirect("/overlord-setup-validated");
} else {
res.redirect("/participant-signup-validated");
}
}
});
});
});
app.get('/github_signin', function(req, res) {
// OAuth setup
var oauth = new OAuth2(config.githubClientId, config.githubSecretId, 'https://github.com/', 'login/oauth/authorize', 'login/oauth/access_token');
var authorizeURL = oauth.getAuthorizeUrl({
redirect_uri: current_root_host + 'github-callback',
scope: "user,repo,public_repo,gist"
});
res.redirect(authorizeURL);
});
app.get('/main', [requireUserMiddleWare, lookupMyTeams, lookupFormedTeams, lookupNeedsTeams], function(req, res) {
console.log("!!!: main");
var Team = app.mongo.model('Team');
var specialMsg = req.param('specialMsg');
var specialText = "";
var hasSpecialText = false;
//Special messages
if(specialMsg == "join-team") {
hasSpecialText = true;
specialText = "Congratulations! You've just joined a team. A repository issue was opened to notify the other team members of your presence and track discussions around it.";
} else if(specialMsg == "create-team") {
hasSpecialText = true;
specialText = "Congratulations! Your team has been created.";
} else if(specialMsg == "update-complete") {
hasSpecialText = true;
specialText = "Your team information has been updated.";
}
for(var i=0; i < req.needsTeams.length; i++) {
var currentTeam = req.needsTeams[i];
currentTeam.isParticipant = false;
for(var j=0; j < currentTeam.participants.length; j++) {
//if is populated
if(currentTeam.participants[j]._id === undefined) {
if(req.session.userId == currentTeam.participants[j])
currentTeam.isParticipant = true;
} else {
if(req.session.userId == currentTeam.participants[j]._id)
currentTeam.isParticipant = true;
}
}
}
res.render('main', {
title: 'Hack4Reno',
sectionTitle: 'Main Hub',
userName: req.session.user.login,
userId: req.session.userId,
gravatarURL: getGravatarURL(req),
myTeams: req.myTeams,
formedTeams: req.formedTeams,
needsTeams: req.needsTeams,
organizationName: config.organizationName,
specialText: specialText,
hasSpecialText: hasSpecialText,
newTeam: new Team(),
loggedIn: true
});
});
app.post('/join-team', [requireUserMiddleWare, requireValidTeam], function(req, res, next){
var dataStoreHandler = new DataStoreHandler(app, req.session);
dataStoreHandler.joinTeam(req.team, function(err, team) {
if(err) {
console.log("err: " + JSON.stringify(err));
next(err);
} else {
res.redirect("/main?specialMsg=join-team");
}
});
});
app.post('/approve-team-member', [requireUserMiddleWare, requireTeamMemberMiddleWare], function(req, res, next) {
var team_id = req.body.team_id;
console.log('Team_id=' + team_id);
var Team = app.mongo.model('Team');
Team.find({_id: team_id}, function(err, docs) {
if(err) {
next(err);
} else {
if(docs === undefined || docs === null || docs.length == 0) {
next(new Error("Unable to locate team with criteria."));
} else {
var currentTeam = docs[0];
currentTeam.pendingParticipants.push(req.session.userId);
currentTeam.save(function(err) {
if(err) {
next(err);
} else {
res.redirect("/main?specialMsg=join-team");
}
});
}
}
});
});
app.post('/reject-team-member', requireUserMiddleWare, function(req, res, next) {
//Github magic start
var overlordGithubAPI = new GitHubApi(true);
overlordGithubAPI.authenticatePassword(config.overlordUsername, config.overlordPassword);
var organizationAPI = overlordGithubAPI.getOrganizationApi();
});
app.post('/updateTeam', [requireUserMiddleWare, requireValidTeam, requireTeamMemberMiddleWare], function(req, res, next){
console.log("!!!: updateTeam");
var team_name = req.body.team_name;
var project_description = req.body.project_description;
var publish_project_description_field = req.body.publish_project_description_field;
var need_developers_field = req.body.need_developers_field;
var need_designers_field = req.body.need_designers_field;
var need_ideas_field = req.body.need_ideas_field;
//Check
check(team_name).len(1, 120);
check(project_description).len(0, 2048);
//Sanitize
team_name = sanitize(team_name).xss();
project_description = sanitize(project_description).xss();
//To Booleans
publish_project_description_field = (publish_project_description_field === 'Y');
need_developers_field = (need_developers_field === 'Y');
need_designers_field = (need_designers_field === 'Y');
need_ideas_field = (need_ideas_field === 'Y');
//New participant save
var Participant = app.mongo.model('Participant');
var Team = app.mongo.model('Team');
//Do real updates to the team object
var teamForUpdate = req.team;
teamForUpdate.name = team_name;
teamForUpdate.description = project_description;
teamForUpdate.needsDevelopers = need_developers_field;
teamForUpdate.needsDesigners = need_designers_field;
teamForUpdate.needsIdeas = need_ideas_field;
teamForUpdate.publishProjectDescription = publish_project_description_field;
teamForUpdate.save(function(err) {
if(err) {
next(err);
} else {
if(err) {
next(err);
} else {
res.redirect("/main?specialMsg=update-complete");
}
//var dataStoreHandler = new DataStoreHandler(app, req.session);
//dataStoreHandler.updateTeam(teamForUpdate, function(err, team) {
// if(err) {
// console.log("err: " + JSON.stringify(err));
// next(err);
// } else {
// //console.log("retFromDataStoreHandler=" + JSON.stringify(team));
// res.redirect("/main?specialMsg=update-complete");
// }
//});
}
});
});
app.post('/create-and-join-team', requireUserMiddleWare, function(req, res, next){
var team_name = req.body.team_name;
var project_description = req.body.project_description;
var publish_project_description_field = req.body.publish_project_description_field;
var need_developers_field = req.body.need_developers_field;
var need_designers_field = req.body.need_designers_field;
var need_ideas_field = req.body.need_ideas_field;
//Check
check(team_name).len(1, 120);
check(project_description).len(0, 2048);
//Sanitize
team_name = sanitize(team_name).xss();
project_description = sanitize(project_description).xss();
//To Booleans
publish_project_description_field = (publish_project_description_field === 'Y');
need_developers_field = (need_developers_field === 'Y');
need_designers_field = (need_designers_field === 'Y');
need_ideas_field = (need_ideas_field === 'Y');
//New participant save
var Participant = app.mongo.model('Participant');
var Team = app.mongo.model('Team');
var dataStoreHandler = new DataStoreHandler(app, req.session);
dataStoreHandler.createTeam({
name: team_name,
needsDevelopers: need_developers_field,
needsDesigners: need_designers_field,
needsIdeas: need_ideas_field,
description: project_description,
publishProjectDescription: publish_project_description_field
}, function(err, team) {
if(err) {
console.log("err: " + JSON.stringify(err));
next(err);
} else {
saveInfoToSession(req, {teamId: team._id, teamName: team.name, hasTeam: true});
res.redirect("/main?specialMsg=create-team");
}
});
});
// Quick util functions
function isLoggedIn(req) {
return (req.session.isLoggedIn);
}
function saveInfoToSession(req, sessionInfoObject) {
var sessionObjectTemplate = {
pendingTeams: [],
activeTeams: [],
userId: null,
login: null
};
for(var prop in sessionObjectTemplate) {
if(sessionInfoObject[prop] !== undefined){
req.session[prop] = sessionInfoObject[prop];
} else {
//If we have nothing set on the session and it's not defined in the passed in object, set a default value
if(req.session[prop] === undefined) {
req.session[prop] = sessionObjectTemplate[prop];
}
}
}
console.log("Session= " + JSON.stringify(req.session));
}
function getGravatarURL(req) {
return "https://secure.gravatar.com/avatar/" + req.session.user.gravatar_id + "?s=45";
}
//Protect middleware
function requireUserMiddleWare(req, res, next) {
console.log("!!!: requireUserMiddleWare");
try {
if(req.session.githubAccessToken && req.session.user) {
next();
} else {
next(new Error("Invalid credentials"));
}
} catch(e) {
next(e);
}
}
function requireValidTeam(req, res, next) {
console.log("!!!: requireValidTeam");
var teamId = req.body.team_id;
var Team = app.mongo.model('Team');
var currentParticipantId = req.session.userId;
Team.find({_id: teamId}, function(err, docs) {
if(err) {
next(err);
} else {
if(docs.length == 1 && docs[0].githubTeamId) {
var currentDoc = docs[0];
req.team = currentDoc;
next();
} else {
next(new Error("Invalid Team"));
}
}
});
}
function requireTeamMemberMiddleWare(req, res, next) {
console.log("!!!: requireTeamMemberMiddleWare");
var teamId = req.body.team_id;
var Team = app.mongo.model('Team');
var currentParticipantId = req.session.userId;
console.log("teamId=" + teamId);
console.log("currentParticipantId=" + currentParticipantId);
Team.find({_id: teamId}, function(err, docs) {
if(err) {
next(err);
} else {
if(docs.length == 1 && docs[0].githubTeamId) {
var currentDoc = docs[0];
var foundMatch = false;
for(var i=0; i < currentDoc.participants.length; i++) {
if(currentDoc.participants[i] == currentParticipantId) {
foundMatch = true;
return next();
}
}
if(!foundMatch) {
console.log("ERROR!!! No match!");
next(new Error("Access Denied"));
}
} else {
console.log("ERROR!!! No docs!");
next(new Error("Access Denied. Invalid team."));
}
}
});
}
function lookupMyTeams(req, res, next) {
console.log("!!!: lookupMyTeams");
var Team = app.mongo.model('Team');
var currentParticipantId = req.session.userId;
Team.where('participants').in([currentParticipantId]).populate('participants').run(function(err, docs) {
if(err) {
next(err);
} else {
req.myTeams = docs;
next();
}
});
}
function lookupFormedTeams(req, res, next) {
var Team = app.mongo.model('Team');
Team.$where('this.participants.length >= (this.maxTeamSize) || (this.needsIdeas === false && this.needsDesigners === false && this.needsDevelopers === false)').populate('participants').run(function(err, docs) {
if(err) {
next(err);
} else {
req.formedTeams = docs;
next();
}
});
}
function lookupNeedsTeams(req, res, next) {
var Team = app.mongo.model('Team');
Team.$where('this.participants.length < this.maxTeamSize && (this.needsDevelopers === true || this.needsDesigners === true || this.needsIdeas === true)').populate('participants').exec(function(err, docs) {
if(err) {
next(err);
} else {
req.needsTeams = docs;
next();
}
});
}
//Maintenance middleware
function maintenanceMiddleware(req, res, next) {
if(config.maintenaceMode === true) {
res.redirect("/maintenance");
} else {
next();
}
}
app.mongo = require('./models')(config.mongourl);
app.config = config;
app.listen(portNumber);
console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env);