-
Notifications
You must be signed in to change notification settings - Fork 1
/
operations.js
477 lines (377 loc) · 15.1 KB
/
operations.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
var mandrill = require('mandrill-api/mandrill');
var mandrillClient = null;
var crypto = require('crypto');
var jxutils = require('jxutils');
var jade = require('jade');
exports.forgot = function(link) {
// get link data
var data = link.data || {};
// set params
link.params = link.params || {};
// get the Mandrill Api Key
if (!link.params.mandrillKey) {
link.send(400, 'ERROR_MISSING_MANDRILL_API_KEY');
return;
}
var username = (data.username || '').trim();
delete data.username;
// send error message if user not provided
if (!username) {
return link.send(400, 'ERROR_MISSING_USERNAME');
}
// get user
getUser(link, username, null, function(err, user, usersCol) {
// handle error
if (err) {
link.send(400, err.message || err);
return;
};
// generate the token
var token = generateToken(10);
var resetLink = 'http://' + link.req.headers.host + '/@/' + link.operation.module + '/reset?username=' + username + '&token=' + token;
var updateObj = {
$set : {}
}
// add the token to the user
updateObj.$set[link.params.tokenkey] = token;
usersCol.update({ _id: user._id }, updateObj, function (err) {
if (err) {
link.send(400, err);
}
// create the mail data
var mailData = {
template: (typeof link.params.template === 'object') ? link.params.template[link.session.locale] : link.params.template,
sender: link.params.sender,
mergeVars: [
{
name: 'recover_link',
content: resetLink
}
]
}
mandrillClient = mandrillClient || new mandrill.Mandrill(link.params.mandrillKey);
// check if a custom code for the receiver exists
if (link.params.customReceiverHandler) {
M.emit(link.params.customReceiverHandler, { user: user, link: link }, function (err, receiver) {
if (err) {
link.send(500, err);
}
mailData.receiver = receiver;
// send mail
sendMail(mandrillClient, mailData, function (err) {
if (err) {
link.send(500, err);
}
// operation complete
link.send(200);
});
});
} else {
mailData.receiver = username;
// send mail
sendMail(mandrillClient, mailData, function (err) {
if (err) { return link.send(500, err); }
// operation complete
link.send(200);
});
}
});
}, link);
};
// jade reset template
var template = null;
exports.reset = function(link) {
// the reset form is requested
if (link.req.method === 'GET') {
if (!link.query.token || !link.query.username) {
return link.send(400, 'ERROR_INVALID_RESET_LINK');
}
// get the token and username
var token = link.query.token;
var username = link.query.username;
// check if a jade template file exists
if (link.params.templateFile) {
var templatePath = M.app.getPath() + '/' + link.params.templateFile;
// compile jade file
try {
template = template || jade.compileFile(templatePath);
} catch (err) {
return link.send(500, err);
}
var data = {
token: token,
username: username
};
// set response headers
link.res.setHeader('content-type', 'text/html');
link.send(200, template(data));
return;
} else {
// set response headers
link.res.setHeader('content-type', 'text/html');
link.send(200, '<form method="POST"><table><tr><td>New password: </td><td><input name="password" type="password"></td></tr><tr><td>Retype password: </td><td><input name="repassword" type="password"></td></tr><tr><td></td><td><button type="submit">Submit</button></td></tr><input name="token" type="hidden" value="' + token + '"><input name="username" type="hidden" value="' + username + '"></form>');
return;
}
}
// the reset form is submitted
if (link.req.method === 'POST') {
var password = (link.data.password || '').trim();
var repassword = (link.data.repassword || '').trim();
var token = (link.data.token || '').trim();
var username = (link.data.username || '').trim();
if (!link.data.password) {
return link.send(400, 'ERROR_MISSING_PASSWORD');
}
if (link.data.password !== link.data.repassword) {
return link.send(400, 'ERROR_PASSWORDS_DO_NOT_MATCH');
}
// TODO make some configurable regexp password policy
// handle hash
switch (link.params.hash) {
case 'md5':
case 'sha1':
var hash = crypto.createHash(link.params.hash);
hash.update(password);
password = hash.digest('hex').toLowerCase();
break;
case 'sha256':
case 'sha512':
var hash = crypto.createHash(link.params.hash);
hash.update(password);
password = hash.digest('hex').toLowerCase();
break;
case 'none':
break;
default:
return link.send(400, link.params.hash ? 'ERROR_MISSING_HASH_ALGORITHM' : 'ERROR_INVALID_HASH_ALGORITHM');
}
// get user
getUser(link, username, null, function(err, user, usersCol) {
// handle error
if (err) {
link.send(400, err.message || err);
return;
}
// check to see if the token matches
if (!token || jxutils.findValue(user, link.params.tokenkey) !== token) {
return link.send(400, 'ERROR_INVALID_RESET_TOKEN');
}
// change the password
var updateObj = {
$set: {},
$unset: {}
};
// change the password
updateObj['$set'][link.params.passkey] = password;
// delete the security token
updateObj['$unset'][link.params.tokenkey] = 1;
usersCol.update({ _id: user._id }, updateObj, { multi: true }, function (err) {
if (err) { return link.send(400, err); }
// check if the reset on.success handler exists
if (link.params.on && link.params.on.success) {
M.emit(link.params.on.success, { user: user, link: link });
}
if (link.params.resetRedirect) {
link.res.headers.location = 'http://' + link.req.headers.host + link.params.resetRedirect;
return link.send(302);
}
link.send(200, 'Password reset');
});
});
}
};
exports.logout = function(link) {
M.session.get(link, function(link) {
if (!link.session._uid) {
return link.send(400, 'ERROR_NOT_LOGGEN_IN');
}
link.session.end(true, function() {
link.send(200);
});
});
};
exports.userInfo = function(link) {
// send no cache headers IE bug
link.res.headers['cache-control'] = 'no-cache';
M.session.get(link, function(link) {
// we intentionally do not reply with a non-200 status
// because we want to avoid the browser showing an error
if (link.session._rid == M.config.app.publicRole || !link.session._uid) {
link.send(200);
return;
}
// TODO remove critical or unnecessary data from the session
link.send(200, link.session);
});
};
exports.login = function(link) {
// send no cache headers IE bug
link.res.headers['cache-control'] = 'no-cache';
// already logged in
if (link.session._rid != M.config.app.publicRole && link.session._uid) {
link.send(400, 'ERROR_ALREADY_LOGGEN_IN');
return;
}
// get link data
var data = link.data || {};
// set params
link.params = link.params || {};
link.params.on = link.params.on || {};
var username = (data.username || '').trim();
delete data.username;
var password = (data.password || '').trim();
delete data.password;
var additionals = data;
// user or password not provided
if (!username || !password) {
return link.send(400, username ? 'ERROR_MISSING_PASSWORD' : 'ERROR_MISSING_USERNAME');
}
// get user
getUser(link, username, password, function(err, user) {
// handle error
if (err) {
link.send(400, err.message || err);
return;
}
// set user additionals
user.additionals = additionals;
function userInfoCallback(err, userInfo) {
// handle error
if (err) {
link.send(403, err.message || err);
return;
}
// start session
M.session.start(link, userInfo.rid, userInfo.uid, userInfo.locale, userInfo.data, function(err, session) {
// send user info data
link.send(200, userInfo.data);
});
}
if (!link.params.on || !link.params.on.userInfo) {
userInfoCallback('You must define a userInfo handler event with handlers' +
' in the form of function(user, session, callback) { ... }' +
' where the callback will be called with an error (possibly null) and an' +
' object of the form: { rid: …, uid: …, locale: …, data: … }.' +
' The data is an optional hash.');
} else {
M.emit(link.params.on.userInfo, user, link.session, userInfoCallback);
}
}, link);
};
function sendMail (client, data, callback) {
callback = callback || function () {};
if (!data) {
return callback('ERROR_MISSING_EMAIL_DATA');
}
var template = {
'template_name': data.template,
'template_content': [],
'message': {
'to': [{
'email': data.receiver,
'type': 'to'
}],
'from_email': data.sender,
'from_name': 'Jillix Support Team',
'global_merge_vars': data.mergeVars
}
};
client.messages.sendTemplate(template, function(result) {
//check to see if rejected
if (result[0].status === 'rejected' || result[0].status === 'invalid') {
callback(result[0].reject_reason || 'Error on sending email, check if the email address provided is valid');
} else {
callback(null);
}
}, function(e) {
// Mandrill returns the error as an object with name and message keys
console.log('A mandrill error occurred: ' + e.name + ' - ' + e.message);
callback(e.name + ' - ' + e.message);
});
}
function generateToken(length) {
var token = '';
var possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
for (var i = 0; i < length; i++) {
token += possible.charAt(Math.floor(Math.random() * possible.length));
}
return token;
}
function getUser(link, username, password, callback) {
if (!link.params) {
return callback(new Error('Missing operation parameters'));
}
M.datasource.resolve(link.params.ds, function(err, ds) {
if (err) { return callback(err); }
M.database.open(ds, function(err, db) {
if (err) { return callback(err); }
db.collection(ds.collection, function(err, collection) {
if (err) { return callback(err); }
var filter = {};
filter[link.params.userkey] = new RegExp('^' + username + '$', 'i');
if (password !== null) {
// 'md5-32/sha1-40/sha256-64/auto'
switch (link.params.hash) {
case 'md5':
case 'sha1':
var hash = crypto.createHash(link.params.hash);
hash.update(password);
password = hash.digest('hex').toLowerCase();
break;
case 'sha256':
case 'sha512':
var hash = crypto.createHash(link.params.hash);
hash.update(password);
password = hash.digest('hex').toLowerCase();
break;
case 'none':
break;
default:
return callback(link.params.hash ? 'ERROR_MISSING_HASH_ALGORITHM' : 'ERROR_INVALID_HASH_ALGORITHM');
}
filter[link.params.passkey] = password;
}
function userCheckCallback(user, collection) {
if (link.params.on && link.params.on.userCheck) {
M.emit(link.params.on.userCheck, user, collection, link.session, callback);
} else {
callback(null, user, collection);
}
}
if (link.params.on && typeof link.params.on.query === 'string') {
var customData = {
filter: filter,
form: {
username: username,
password: password
}
};
M.emit(link.params.on.query, link, link.params, customData, function (err, data) {
// handle error
if (err) { return callback(err); }
// find one
collection.findOne(data.filter, function(err, user) {
// handle error
if (err) { return callback(err); }
// no user
if (!user) {
return callback('ERROR_USER_OR_PASS_NOT_VALID');
}
// user found
userCheckCallback(user, collection);
});
});
return;
}
collection.findOne(filter, function(err, user) {
if (err) { return callback(err); }
if (!user) {
return callback('ERROR_USER_OR_PASS_NOT_VALID');
}
// user found
userCheckCallback(user, collection);
});
});
});
});
}