/
server.js
467 lines (418 loc) · 12.8 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
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
//import modules
var express = require('express'),
connect = require('connect'),
ejs = require('ejs'),
http = require('http'),
mongoose = require('mongoose'),
passport = require('passport'),
GooglePass = require('passport-google').Strategy,
GithubPass = require('passport-github').Strategy,
models = require('./models');
/*
configure server to run locally or on heroku.
run the server with node server.js <mode> <port>
if mode is set to "production", server will connect to the h@b production or test database
and be served up on the heroku url.
if mode is set to "local", server will try to connect to a local mongo instance named habitat
and be served up on localhost:<port>.
mode defaults (if no argument or garbage is provided) to using the test database and local url.
port defaults to 8000
*/
var port = process.argv[3] || 8000,
heroku_url = "http://habitat.hackersatberkeley.com",
local_url = "http://localhost:"+port,
local_db = 'mongodb://localhost:27017/habitat',
remote_db = process.env.TMPMONGOHQ_URL || "mongodb://hackallnight:yoloswag2013@ds029847.mongolab.com:29847/hab_testing",
GIT_ID = process.env.gitID || "1771ed921581c00d677e",
GIT_SECRET = process.env.gitSecret || "f107369fd2c33bbbed9bd25132edbe9df717bdea",
MONGO_URI = remote_db,
SITE_URL = local_url;
//console.log(process.argv);
if (process.argv[2] == "production") {
SITE_URL = heroku_url;
}
else if (process.argv[2] == "local") {
MONGO_URI = local_db;
}
console.log("h@bitat running at", SITE_URL, "\nconnected to db", MONGO_URI);
// instantiate the app and connect to the database
var app = module.exports = express.createServer(),
db = mongoose.connect(MONGO_URI);
/* START UTILITY FUNCTIONS */
function errorCallback(err) {
if (err) {
console.log(err);
}
};
function ensureAuthenticated(failureUrl) {
return function(req, res, next) {
if (req.isAuthenticated())
next();
else
res.redirect(failureUrl);
}
}
function forceAbsolute(url) {
if (url && url.indexOf('://') < 0) {
url = "http://" + url;
}
return url;
}
function stripSpaces(str) {
return str.replace(/^\s+|\s+$/g,'');
}
function stripPunct(str) {
return str.replace(/[^a-zA-Z0-9]+/g, '').replace('/ {2,}/',' ');
}
function shuffle(arr) {
var m = arr.length, t, i;
while (m) {
i = Math.floor(Math.random() * m--);
t = arr[m];
arr[m] = arr[i];
arr[i] = t;
}
return arr;
}
/* END UTILITY FUNCTIONS */
// configure app and modules
app.configure(function() {
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser());
app.use(express.session({secret: 'autobahn'}));
app.use(passport.initialize());
app.use(passport.session());
app.use(app.router);
app.use('/', express.static(__dirname + '/public'));
app.use(express.favicon(__dirname + '/public/img/favicon.ico'));
});
// instantiate Mongoose models
var User = mongoose.model('User', models.UserSchema),
Hack = mongoose.model('Hack', models.HackSchema),
Event = mongoose.model('Event', models.EventSchema);
/* START AUTHENTICATION FUNCTIONS */
passport.serializeUser(function(user, done) {
done(null, user._id);
});
passport.deserializeUser(function(id, done) {
User.findById(id, function (err, user) {
done(err, user);
});
});
passport.use(
new GithubPass({
clientID: GIT_ID,
clientSecret: GIT_SECRET,
callbackURL: SITE_URL+"/auth/github/callback",
}, function(accessToken, refreshToken, profile, done) {
User.findOne({"github.id": profile.id}, function(err, doc) {
if (!doc) {
doc = new User();
doc.info.name = profile._json.name;
}
doc.github.id = profile.id;
doc.github.username = profile.username;
doc.github.url = profile.profileUrl;
doc.github.avatarUrl = profile._json.avatar_url.split('?')[0];
doc.github.name = profile._json.name;
doc.github.email = profile.emails[0]["value"];
doc.save(errorCallback);
done(err, doc);
});
}
));
app.get('/login', passport.authenticate('github'));
app.get('/auth/github/callback',
passport.authenticate('github', {
failureRedirect: '/', //add failure page
}),
function(req, res) {
res.redirect('/users/me');
}
);
/* END AUTHENTICATION FUNCTIONS */
/* START REQUEST HANDLERS */
app.get('/logout', function(req, res) {
req.logout();
res.redirect('/');
});
app.get('/users', function(req, res) {
User.find({}, function(err, docs) {
res.render('hackers', {
title: 'Hackers',
user: req.user,
users: shuffle(docs),
});
});
});
app.get('/users/:username', function(req, res) {
function prepare_response(err, doc, myself) {
if (!myself || myself!=true) {
myself = false;
}
if (err) {
res.redirect('https://github.com/'+doc.github.username);
} else {
Hack.find({
'team': {
$all: [doc.github.username],
}
}, function(err, docs) {
res.render('profile', {
title: 'Profile',
user: req.user,
viewing: doc,
hacks: docs,
quote: '\"There are few sources of energy so powerful as a procrastinating college student.\" -- paul graham',
myself: myself
});
});
}
}
if (req.params.username == "me") {
if (req.user) {
prepare_response(false, req.user, true);
} else {
passport.authenticate("github");
}
} else {
if (req.user && req.params.username == req.user.github.username) {
prepare_response(false, req.user, true);
} else {
User.findOne({
"github.username": req.params.username,
}, prepare_response);
}
}
});
// need to be able to edit profile page
app.post('/users/:username', function(req, res) {
console.log("updating");
if (req.params.username == "me") {
var username = req.user.github.username;
} else {
var username = req.params.username;
if (req.user.github.username != username) {
res.redirect("/users/"+req.params.username);
}
}
console.log(username);
User.findOne({
"github.username": username
}, function(err, user) {
console.log("found the user: "+user);
if (err) {
console.log(err);
res.redirect("/users/me");
} else {
user.info.name = req.body.user.name || user.info.name;
user.info.email = req.body.user.email || user.info.email;
user.info.blurb = req.body.user.blurb || user.info.blurb;
user.save(function(e) {
if (e) {
console.log("Ran into error: "+e);
} else {
console.log("Saved.");
}
});
}
});
});
function project_filter(req, res, page, searchstr) {
/* Return many objects that correspond to the given page and query. */
var query = Hack.find({});
if (searchstr.length > 0) {
var constraints = [];
var terms = searchstr.split(' ');
terms.forEach(function(term) {
var termrx = new RegExp(term, "i");
constraints.push({'title': { $regex: termrx}});
constraints.push({'blurb': { $regex: termrx}});
});
constraints.push({'tags': { $in: terms }});
query.or(constraints);
}
//query.skip(page * 30);
//query.limit(30);
query.exec(function(err, docs) {
res.render('hacks', {
title: 'Hacks',
user: req.user,
hacks: shuffle(docs),
});
});
};
app.get('/projects', function(req, res) {
project_filter(req, res, 0, "");
});
app.get('/projects/filter/:page/:query', function(req, res) {
project_filter(req, res, req.params.page, req.params.query);
});
app.get('/projects/:id', function(req, res) {
Hack.findOne({
"hackid": req.params.id,
}, function(err, doc) {
var team = {};
for (var i=0; i<doc.team.length; i++) {
if(doc.team[i]) {
team[doc.team[i]] = {
name: doc.team[i],
avatarUrl: "https://s3.amazonaws.com/hackerfair/default-photo.jpg"
};
}
}
User.where('github.username').in(doc.team).exec(function(err, docs) {
for (var i=0; i<docs.length; i++) {
team[docs[i].github.username] = {
name: docs[i].info.name || docs[i].github.name || docs[i].github.username,
avatarUrl: docs[i].github.avatarUrl,
};
}
console.log("LINE"+JSON.stringify(doc));
res.render('hack', {
title: doc.title,
user: req.user,
hack: doc,
team: team,
names: doc.names
});
});
});
});
app.get('/projects/:id/edit', ensureAuthenticated('/login'), function(req, res) {
Hack.findOne({
"hackid": req.params.id,
}, function(err, doc) {
if (doc.owners.indexOf(req.user._id) < 0) {
res.redirect('/projects/'+req.params.id);
}
else {
User.where('_id').in(doc.owners).exec(function(err, docs) {
res.render('edit_hack', {
title: doc.title,
user: req.user,
hack: doc,
owners: docs.map(function(owner) {
return owner.github.username;
}),
});
});
}
});
});
app.post('/projects/:id', ensureAuthenticated('/login'), function(req, res) {
console.log(req.body);
Hack.findOne({
"hackid": req.params.id,
}, function(err, doc) {
if (doc.owners.indexOf(req.user._id) < 0) {
res.redirect('/projects/'+req.params.id);
} else {
console.log("Goodbye"+JSON.stringify(req.body));
doc.title = req.body.title;
doc.source = forceAbsolute(req.body.source);
doc.demo = forceAbsolute(req.body.demo);
doc.video = forceAbsolute(req.body.video);
doc.picture = forceAbsolute(req.body.picture);
doc.blurb = req.body.blurb;
doc.tags = req.body.tags.toLowerCase().split(',').map(stripSpaces);
doc.comments = req.body.comments;
doc.save(function(err, doc) {
res.redirect('/projects/'+doc.hackid);
});
}
});
});
app.get('/submit', ensureAuthenticated('/login'), function(req, res) {
res.render('submit', {
title: 'Submit Hack',
user: req.user,
});
});
app.get('/summary/:eventname', function(req, res) {
if (false) {//['syadlowsky', 'viyer', 'vedantk', 'geraldgfong', 'nelsonz'].indexOf(req.user.github.username) < 0) {
res.redirect('/hacks');
} else {
var query = Hack.find({event:req.params.eventname});
query.exec(function(err, docs) {
console.log("Creating summary of event: "+req.params.eventname);
docs = shuffle(docs);
var respString = "";
for (var i = 0; i < docs.length; i++) {
console.log("Making report for "+docs[i]);
respString += docs[i].title+"\n";
respString += Array(docs[i].title.length+1).join("-")+"\n";
respString += "Description: "+docs[i].blurb+"\n";
respString += " Team: "+docs[i].team.join(", ")+"\n";
respString += "\n";
}
console.log("Summary generation complete.");
res.attachment(req.params.eventname+".txt");
res.end(respString);
console.log("Completed transfer");
});
}
});
app.post('/submit', ensureAuthenticated('/login'), function(req, res) {
Hack.find({}, function(err, docs) {
var address = stripPunct(req.body.title.toLowerCase()),
collisions = 0;
docs.map(function(doc) {
collisions += (stripPunct(doc.title.toLowerCase()) == address ? 1 : 0);
}).length;
var now = new Date();
Event.findOne({start: {$lt: now}, end: {$gt: now}}, function(err, event){
var name = "on-going-hacks";
if(!err && event){
name = event.name;
}
var hack = new Hack({
title: req.body.title,
owners: [req.user._id],
source: forceAbsolute(req.body.source),
demo: forceAbsolute(req.body.demo),
video: forceAbsolute(req.body.video),
picture: forceAbsolute(req.body.picture),
blurb: req.body.blurb,
tags: req.body.tags.toLowerCase().split(',').map(stripSpaces),
hackid: address+"-"+Math.random().toString(36).substring(2, 8)+(collisions ? collisions : ""),
team: req.body.team.split(',').map(stripSpaces),
booth: req.body.booth,
event: name,
comments: [req.body.comments]
});
hack.save(function(err, doc) {
if (err) {
console.log(err);
}
res.redirect('/projects/'+hack.hackid);
});
});
});
});
app.get('/', function(req, res) {
res.render('index', {
title: 'Home',
user: req.user,
});
});
app.post('/projects/:id/comment', function(req,res) {
console.log("HELLO");
var newComment = {poster: req.body.postername, comment: req.body.postercomment};
console.log("WTF"+JSON.stringify(newComment));
Hack.update({
"hackid": req.params.id,
}, { $push: { comments: newComment } },
function(err, doc, raw) {
console.log("NOOO"+JSON.stringify(doc));
console.log("RAW: " + raw);
console.log("ERR: " + err);
res.redirect('/projects/'+req.params.id);
});
});
/* END REQUEST HANDLERS */
// listen for requests on the specified port
app.listen(process.env.PORT || port);