-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathserver.js
executable file
·479 lines (429 loc) · 13.1 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
468
469
470
471
472
473
474
475
476
477
478
479
var express = require('express');
var fs = require('fs');
var app = express.createServer();
var mongo = require('mongoskin');
var db = mongo.db('mongodb://localhost:27017/happy');
var SkinStore = require('connect-mongoskin');
var bcrypt = require('bcrypt');
var request = require('request');
// mailer
var nodemailer = require('nodemailer');
var smtpTransport = nodemailer.createTransport("SMTP", {
service: "Gmail",
auth: {
user: 'moosefrans@gmail.com',
pass: process.argv[2] || 'password'
}
});
/**
* User: {
* username: unique,
* password: ***,
* email: optional, unique,
* sms: optional, unique,
* twitter: optional, unique,
* color: optional, default=purple,
* ignore: default=false, optional, -- don't send emails if true.
* happiness: default=0
* }
*/
var users = db.collection('users');
users.ensureIndex({username: 1});
users.ensureIndex({email: 1});
users.ensureIndex({sms: 1});
var passwordCodes = db.collection('password_codes');
passwordCodes.ensureIndex({user: 1});
/**
* Happiness: {
* username: String,
* date: Date,
* message: String
* }
*/
function happies() {
return db.collection(new Date().getFullYear() + 'happies');
}
happies().ensureIndex({username: 1});
function validateUsername(username) {
return username.length < 21 && /^[a-zA-Z0-9\_]+$/.test(username);
}
function validateEmail(email) {
var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
/** Generate random session ID. */
function randomId() {
return Math.random().toString(36).substr(2);
}
function changePassword(username, password, params, cb) {
bcrypt.genSalt(10, function(err, salt) {
if (err) {
cb(err);
} else {
bcrypt.hash(password, salt, function(err, hash) {
if (err) {
cb(err);
} else {
params = params || {};
params.hash = hash;
users.findAndModify({username: username}, {}, {$set: params}, {new: true}, function(err, user) {
cb(err, user);
});
}
});
}
});
}
function loginRequired(req, res, next) {
if (!req.session.username) {
res.send(401);
return;
}
next();
}
function findRandomHappiness(year, username, goBack, cb) {
db.collection(year + 'happies').find({username: username}).toArray(function(err, h) {
if (!err) {
if (h.length > 0) {
var hh = h[Math.floor(Math.random() * h.length)];
var date = (hh.date.getMonth() + 1) + '/' + hh.date.getDate() + '/' + hh.date.getFullYear();
var message = hh.message;
cb(null, {happiness: message, date: date});
} else {
// Go back one year.
if (goBack) {
findRandomHappiness(year - 1, username, false, cb);
} else {
cb('Nothing found.');
}
}
} else {
cb(err);
}
});
}
function countHappiness(username, cb) {
happies().count({username: username}, function(err, count) {
cb(count || 0);
});
}
// Initialize main server
app.use(express.bodyParser());
app.use(express.cookieParser());
app.use(express.static(__dirname + '/public'));
app.use(express.session({
secret: process.argv[3],
maxAge : new Date(Date.now() + 2628000000),
store: new SkinStore(db)
}));
app.set('view engine', 'ejs');
app.set('views', __dirname + '/views');
app.get('/', function(req, res) {
if (req.session.username) {
users.findOne({ username: req.session.username }, function(err, user) {
if (user) {
countHappiness(user.username, function(count) {
user.currentHappinesses = count;
res.render('index', { user: JSON.stringify(user) });
});
} else {
res.render('index', { user: '' });
}
});
} else {
res.render('index', { user: '' });
}
});
// Password reset page.
app.get('/reset/:key', function(req, res) {
var key = req.params.key;
passwordCodes.findById(key, function(err, code) {
if (code) {
users.findById(code.user, function(err, user) {
if (user) {
res.render('reset', {user: user})
} else {
res.redirect('/');
}
});
} else {
res.redirect('/');
}
});
});
// Save new password, redirect to index.
app.post('/reset/:key', function(req, res) {
var key = req.params.key;
var newPassword = req.body.password;
var confirmPassword = req.body.confirm;
if (newPassword !== confirmPassword) {
res.send({err: 'Passwords do not match.'});
return;
}
passwordCodes.findById(key, function(err, code) {
if (code) {
users.findById(code.user, function(err, user) {
if (user) {
changePassword(user.username, newPassword, {}, function(err) {
if (err) {
res.send({err: 'An unexpected error has occurred. Please email michelle@michellebu.com if this problem persists.'});
} else {
res.send(200);
}
});
} else {
res.send({err: 'This password reset link has expired. Please try again.'});
}
});
passwordCodes.removeById(code._id);
} else {
res.send({err: 'This password reset link has expired. Please try again.'});
}
});
});
// Triggered when the client closes the window; saves their color choice.
app.post('/leave', loginRequired, function(req, res) {
users.update({ username: req.session.username }, { $set: { color: req.body.color } }, {}, function() {
res.send(200);
});
});
// Removes session from user on logout.
app.post('/logout', loginRequired, function(req, res) {
delete req.session.username;
res.send(200);
});
// Retrieves a random happiness for the user.
app.get('/random_happy', loginRequired, function(req, res) {
findRandomHappiness(new Date().getFullYear(), req.session.username, true, function(err, happiness) {
if (err) {
res.send({err: 'Nothing found'});
} else {
res.send(happiness);
}
});
});
// logs in a user, saves session ID, errors if already taken username.
app.post('/login', function(req, res) {
if (!req.body.username || !req.body.password) {
res.send({err: 'Please enter a username and password.'});
return;
}
users.findOne({username: req.body.username.toLowerCase()}, function(err, user) {
if (!err && user && user.hash) {
bcrypt.compare(req.body.password, user.hash, function(err, match) {
if (match) {
req.session.username = req.body.username.toLowerCase();;
countHappiness(user.username, function(count) {
user.currentHappinesses = count;
res.send({user: user});
});
} else {
res.send({err: 'Password is incorrect.'});
}
});
} else {
res.send({err: 'Username does not exist.'});
}
});
});
app.post('/register', function(req, res) {
if (!req.body.username || !req.body.password) {
res.send({err: 'Please enter a username and password.'});
return;
}
if (!validateUsername(req.body.username)) {
res.send({err: 'Your username can contain up to 20 letters, numbers, or _.'});
return;
}
users.findOne({username: req.body.username.toLowerCase()}, function(err, user) {
if (!user) {
bcrypt.genSalt(10, function(err, salt) {
bcrypt.hash(req.body.password, salt, function(err, hash) {
// Save new user to database.
users.insert({
twitter: '',
email: '',
sms: '',
ignore: false,
color: '',
username: req.body.username.toLowerCase(),
hash: hash,
happiness: 0,
count: 0
}, {}, function(err, result) {
if (err) {
res.send({err: 'Username is taken.'});
} else {
req.session.username = req.body.username.toLowerCase();
res.send({user: result});
}
});
});
});
} else {
res.send({err: 'Username is taken.'});
}
});
});
// Saves a happiness.
app.post('/happy', loginRequired, function(req, res) {
happies().insert({
username: req.session.username,
date: new Date(),
message: req.body.message
}, function(err) {
if (!err) {
users.update({username: req.session.username},
{$inc: {happiness: 1}},
{},
function(err) {
res.send(200);
}
);
} else {
res.send({err: 'Whoops, try again later.'});
}
});
});
app.post('/ignore', loginRequired, function(req, res) {
res.send(200);
});
// Saves user email, sms, twitter settings, errors if already used.
app.post('/save', loginRequired, function(req, res) {
if (req.body.email && !validateEmail(req.body.email)) {
res.send({err: 'The email you entered is not valid.'});
return;
}
var sms = req.body.sms;
if (sms) {
sms = sms.replace(/\D/g, '');
}
// TODO: make this not so stupid of a codepath.
if (req.body.password) {
changePassword(req.body.username, req.session.username, {
email: req.body.email,
sms: sms
}, function(err, user) {
if (!err) {
res.send({user: user, result: 'Details successfully saved.'});
} else {
res.send({err: err});
}
});
} else {
users.findAndModify(
{username: req.session.username},
{}, // sort
{
$set: {
email: req.body.email,
sms: sms
}
},
{new: true},
function(err, user) {
if (!err) {
res.send({user: user, result: 'Details successfully saved.'});
} else {
res.send({err: err});
}
}
);
}
});
// Sends a lost password email.
app.post('/forgot', function(req, res) {
function findByQuery(query, input) {
users.findOne(query, function(err, user) {
if (user && validateEmail(user.email)) { // we need to validate again because legacy.
// TODO: make this less shitty.
passwordCodes.insert({user: user._id}, function(err, result) {
if (!err) {
var result = result[0];
var randomURL = 'http://happinessjar.com/reset/' + result._id;
var msg = {
text: 'Hi, ' + user.username + '. Please visit ' + randomURL + ' to change your password to something that\'s easy to remember.',
from: 'Happiness Moose <moosefrans@gmail.com>',
to: user.email,
subject: '[Happiness Jar] Reset your password.',
};
smtpTransport.sendMail(msg, function(err, ignore) {
if (err) {
res.send({err: 'An unexpected error occurred. Please email michelle@michellebu.com if this keeps happening.'});
console.log('MAILER ERROR: ' + err);
} else {
res.send({email: user.email});
}
});
} else {
res.send({err: 'An unexpected error occurred. Please email michelle@michellebu.com if this keeps happening.'});
}
});
} else if (user) {
res.send({err: 'We could not find a valid email address associated with ' + input + '. Please email michelle@michellebu.com to get your password reset.'});
} else {
res.send({err: 'We could not find an account associated with ' + input + '.'});
}
});
}
var input = req.body.username;
if (input) {
findByQuery({'$or': [{email: input}, {username: input}]}, input);
} else {
// Shouldn't get here.
res.send({err: 'Please enter a username or email.'});
}
});
// Handle a new text message.
// Query users for that phone number. If ':(', send back a random happiness.
// Otherwise, store it.
app.post('/new_text', function(req, res) {
var sms = req.body;
if (sms && sms.text && sms.number) {
users.findOne({sms: sms.number}, function(err, user) {
if (user && user.username) {
// Trim text.
if (sms.text.replace(/(^\s*)|(\s*$)/g, '') === ':(') {
findRandomHappiness(new Date().getFullYear(), user.username, true, function(err, happiness) {
if (!err) {
request({
method: 'POST',
url: 'https://www.gvmax.com/api/send',
form: {
callbackUrl: 'http://happinessjar.com/ignore',
pin: '40d1165fdb6442e3be3f3a4d1d3f8dec',
number: sms.number,
text: happiness.happiness
}
}, function(err, msg, response) {
// TODO: figure out how to handle these.
// For now we're just assuming success.
if (err) {
console.log(err);
}
});
}
});
} else {
happies().insert({
username: user.username,
date: new Date(),
message: sms.text
}, function(err, result) {
if (!err) {
users.update({username: user.username},
{ $inc: { happiness: 1 } },
{},
function(err) {
}
);
}
});
}
}
});
}
// always send ok.
res.send(200);
});
app.listen(8009);