This repository was archived by the owner on Nov 5, 2023. It is now read-only.
forked from substance/substance-legacy
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
746 lines (630 loc) · 23.6 KB
/
server.js
File metadata and controls
746 lines (630 loc) · 23.6 KB
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
var express = require('express');
var app = express.createServer();
var http = require('http');
var crypto = require('crypto');
var fs = require('fs');
var url = require('url');
var Data = require('./lib/data/data');
var _ = require('underscore');
var CouchClient = require('./lib/data/lib/couch-client');
var async = require('async');
var Document = require('./src/server/document');
var User = require('./src/server/user');
var Filters = require('./src/server/filters');
var HTMLRenderer = require('./src/server/renderers/html_renderer');
var nodemailer = require('nodemailer');
nodemailer.sendmail = true;
// Google Analytics (TODO: move somewhere else)
var gaScript = [
"<script type=\"text/javascript\">",
" var _gaq = _gaq || [];",
" _gaq.push(['_setAccount', 'UA-25112053-1']);",
" _gaq.push(['_trackPageview']);",
" (function() {",
" var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;",
" ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';",
" var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);",
" })();",
"</script>"
].join('\n');
// App Config
global.config = JSON.parse(fs.readFileSync(__dirname+ '/config.json', 'utf-8'));
global.seed = JSON.parse(fs.readFileSync(__dirname+ '/db/schema.json', 'utf-8'));
// App Settings
global.settings = JSON.parse(fs.readFileSync(__dirname+ '/settings.json', 'utf-8'));
global.db = CouchClient(config.couchdb_url);
var VALIDATE_EMAIL = new RegExp("^(([^<>()[\\]\\\\.,;:\\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,}))$");
// Express.js Configuration
// -----------
app.configure(function() {
var CookieStore = require('cookie-sessions');
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(CookieStore({secret: config.secret}));
app.use(app.router);
app.use(express.static(__dirname+"/public", { maxAge: 41 }));
app.use(express.logger({ format: ':method :url' }));
});
app.configure('development', function() {
// Expose source file in development mode
app.use(express.static(__dirname+"/src", { maxAge: 41 }));
});
function urlToHttpOptions(u) {
fragments = url.parse(u);
return {
host: fragments.hostname,
port: fragments.port,
path: fragments.pathname + (fragments.search || '')
}
}
function letterpress(graph, id, format, response) {
var postData = JSON.stringify({
'format' : format,
'graph': graph,
'id': id
});
var postOptions = urlToHttpOptions(config.letterpress_url+"/convert");
_.extend(postOptions, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(postData)
}
});
var req = http.request(postOptions, function(res) {
response.writeHead(200, res.headers);
res.pipe(response)
});
req.write(postData);
req.end();
};
app.use(function(req, res) {
var path = require('url').parse(req.url).pathname
var fragments = path.split('/');
var username = fragments[1];
var docname = fragments[2] ? fragments[2].split('.')[0] : null;
var format = fragments[2] ? fragments[2].split('.')[1] : null;
var version = fragments[3]; // version
if (username && docname && (req.headers["user-agent"].indexOf('bot.html')>=0 || req.query.static || format)) {
Document.get(username, docname, version, req.session ? req.session.username : null, function(err, nodes, id, authorized, version, published) {
if (err) return res.send({status: "error", error: err});
if (format) {
if (format === "json") return res.json({status: "ok", graph: nodes, id: id, authorized: authorized, version: version, published: published });
letterpress(nodes, id, format, res);
} else {
var graph = new Data.Graph(seed);
graph.merge(nodes);
html = fs.readFileSync(__dirname+ '/templates/doc.html', 'utf-8');
var content = new HTMLRenderer(graph.get(id)).render();
res.send(html.replace('{{{{document}}}}', content));
}
});
} else {
// A modern web-client is talking - Serve the app
serveStartpage(req, res);
}
});
app.enable("jsonp callback");
function serveStartpage(req, res) {
html = fs.readFileSync(__dirname+ '/templates/app.html', 'utf-8');
req.session = req.session ? req.session : {username: null};
function serve() {
getNotifications(req.session.username, function(err, notifications) {
var sessionSeed = _.extend(_.clone(seed), notifications);
res.send(html.replace('{{{{seed}}}}', JSON.stringify(sessionSeed))
.replace('{{{{session}}}}', JSON.stringify(req.session))
.replace('{{{{config}}}}', JSON.stringify(clientConfig()))
.replace('{{{{ga}}}}', gaScript)
.replace('{{{{scripts}}}}', JSON.stringify(scripts())));
});
}
// update session seed every time!
var graph = new Data.Graph(seed).connect('couch', {url: config.couchdb_url});
if (req.session.username) {
graph.fetch({_id: "/user/"+req.session.username}, function(err, nodes) {
req.session.seed = nodes.toJSON();
serve();
});
} else {
serve();
}
}
function findAttributes(member, searchstr, callback) {
db.view('substance/attributes', {key: member}, function(err, res) {
if (err) {
callback(err);
} else {
var result = {};
var count = 0;
_.each(res.rows, function(row) {
if (row.value.name && row.value.name.match(new RegExp("("+searchstr+")", "i"))) {
// Add to result set
if (count < 50) { // 200 Attributes at the most
count += 1;
result[row.value._id] = row.value;
}
}
});
callback(null, result);
}
});
}
function getNotifications(username, callback) {
// Read in reversed order, therefore replaced startkey with endkey
if (!username) return callback(null, {});
db.view('substance/notifications', {endkey: ["/user/"+username], startkey: ["/user/"+username, {}], descending: true, limit: 5}, function(err, res) {
if (err) return callback(err);
var result = {};
async.forEach(res.rows, function(row, callback) {
// Fetch corresponding event
db.get(row.value.event, function(err, event) {
if (err) return callback();
result[row.value._id] = row.value;
result[event._id] = event;
callback();
});
}, function(err) {
callback(null, result);
});
});
}
var graph = new Data.Graph(seed);
graph.connect('couch', {
url: config.couchdb_url,
filters: [
Filters.ensureAuthorized(),
Filters.sanitizeUserInput(),
Filters.logEvents()
]
});
// Serve Data.js backend along with an express server
graph.serve(app);
// Helpers
// -----------
var Helpers = {};
var encryptPassword = function (password) {
var hash = crypto.createHash('sha256');
hash.update(password);
return hash.digest('hex');
}
// Templates for the moment are recompiled every time
_.renderTemplate = function(tpl, view, helpers) {
var source = fs.readFileSync(__dirname+ '/templates/' + tpl + '.html', 'utf-8');
var template = Handlebars.compile(source);
return template(view, helpers || {});
};
_.escapeHTML = function(string) {
return string.replace(/&(?!\w+;)/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
};
function clientConfig() {
return {
"letterpress_url": config.letterpress_url,
"transloadit": _.escapeHTML(JSON.stringify(config.transloadit))
};
}
function scripts() {
if (process.env.NODE_ENV === 'production') {
return settings.scripts.production;
} else {
return settings.scripts.development.concat(settings.scripts.source);
}
}
// Web server
// -----------
app.get('/sitemap.xml', function(req, res) {
Document.recent(3000, '', function(err, nodes, count) {
res.writeHead(200, {'Content-Type': 'text/plain'});
_.each(nodes, function(n) {
if (_.include(n.type, '/type/document')) {
res.write("http://substance.io/"+n.creator.split('/')[2]+"/"+n.name+"\n");
}
});
res.end();
});
});
// Quick search interface (returns found users and a documentset)
app.get('/quicksearch/:search_str', function(req, res) {
Document.find(req.params.search_str, 'keyword', req.session.username, function(err, graph, count) {
User.find(req.params.search_str, function(err, users) {
res.send(JSON.stringify({document_count: count, users: users}));
});
});
});
// Find documents by search string or user
app.get('/documents/search/:type/:search_str', function(req, res) {
var username = req.session ? req.session.username : null
if (req.params.type === 'recent') {
Document.recent(req.params.search_str, username, function(err, graph, count) {
res.send(JSON.stringify({graph: graph, count: count}));
});
} else if(req.params.type === 'subscribed') {
Document.subscribed(username, function(err, graph, count) {
res.send(JSON.stringify({graph: graph, count: count}));
});
} else {
Document.find(req.params.search_str, req.params.type, username, function(err, graph, count) {
res.send(JSON.stringify({graph: graph, count: count}));
});
}
});
// Find documents by search string (full text search in future)
// Or find by user
app.get('/attributes', function(req, res) {
findAttributes(req.query.member, req.query.search_str, function(err, graph) {
res.send(JSON.stringify({graph: graph}));
});
});
app.post('/login', function(req, res) {
var username = req.body.username.toLowerCase(),
password = req.body.password;
var graph = new Data.Graph(seed).connect('couch', {url: config.couchdb_url});
graph.fetch({_id: '/user/'+username}, function(err, nodes) {
if (!err && nodes.length > 0) {
var user = nodes.first();
if (user && username === user.get('username').toLowerCase() && encryptPassword(password) === user.get('password')) {
var seed = {};
seed[user._id] = user.toJSON();
delete seed[user._id].password;
// TODO: Include notifications
getNotifications(username, function(err, notifications) {
req.session = {
username: username.toLowerCase(),
seed: seed
};
res.send({
status: "ok",
username: username,
seed: _.extend(_.clone(seed), notifications)
});
});
} else {
res.send({status: "error"});
}
} else {
res.send({status: "error"});
}
});
});
// Logout
app.post('/logout', function(req, res) {
req.session = {};
res.send({status: "ok"});
});
// Register user
app.post('/register', function(req, res) {
var username = req.body.username,
password = req.body.password,
email = req.body.email,
name = req.body.name;
var graph = new Data.Graph(seed).connect('couch', {url: config.couchdb_url});
if (!username || username.length === 0) {
return res.send({"status": "error", "field": "username", "message": "Please choose a username."});
}
db.view('substance/users', {key: username.toLowerCase()}, function(err, result) {
if (err) return res.send({"status": "error", "field": "all", "message": "Unknown error."});
if (result.rows.length > 0) return res.send({"status": "error", "field": "username", "message": "Username is already taken."});
var user = graph.set('/user/'+username.toLowerCase(), {
type: '/type/user',
username: username,
name: name,
email: email,
password: encryptPassword(password),
created_at: new Date()
});
if (user.validate() && password.length >= 3) {
graph.sync(function(err) {
if (!err) {
var seed = {};
seed[user._id] = user.toJSON();
delete seed[user._id].password;
req.session = {
username: username.toLowerCase(),
seed: seed
};
res.send({
status: "ok",
username: username.toLowerCase(),
seed: seed
});
} else {
return res.send({"status": "error", "field": "all", "message": "Unknown error."});
}
});
} else {
console.log(user.errors);
return res.send({"status": "error", "errors": user.errors, "field": "all", "message": "Some field values are invalid. Please check your input."});
}
});
});
app.post('/updateuser', function(req, res) {
var username = req.body.username;
var graph = new Data.Graph(seed).connect('couch', {url: config.couchdb_url});
graph.fetch({type: '/type/user'}, function(err) {
var user = graph.get('/user/'+username);
if (!user) return res.send({"status": "error"});
user.set({
name: req.body.name,
email: req.body.email,
location: req.body.location,
website: req.body.website,
company: req.body.company,
location: req.body.location
});
// Change password
if (req.body.password) {
user.set({
password: encryptPassword(req.body.password)
});
}
if (user.validate()) {
graph.sync(function(err) {
if (!err) {
var seed = {};
seed[user._id] = user.toJSON();
delete seed[user._id].password;
res.send({
status: "ok",
username: username,
seed: seed
});
req.session.username = username;
req.session.seed = seed;
} else {
return res.send({"status": "error"});
}
});
} else return res.send({"status": "error", "message": "Not valid", "errors": user.errors});
});
});
// Reset password
app.post('/reset_password', function(req, res) {
var username = req.body.username,
tan = req.body.tan,
password = req.body.password;
var graph = new Data.Graph(seed).connect('couch', {url: config.couchdb_url});
graph.fetch({_id: "/user/"+username}, function(err) {
var user = graph.get("/user/"+username);
if (user.get('tan') !== tan) return res.send({"status": "error", "message": "The Password reset token has expired."});
if (password.length < 3) return res.send({"status": "error", "message": "Password is invalid. Be aware that you need 3 characters minimum."});
if (user) {
user.set({
password: encryptPassword(password),
tan: null // reset tan
});
// Auto login
var seed = {};
seed[user._id] = user.toJSON();
delete seed[user._id].password;
req.session = {
username: username.toLowerCase(),
seed: seed
};
graph.sync(function(err) {
if (err) return res.send({"status": "error", "message": "Unknown error."});
res.send({"status": "ok"});
});
} else {
res.send({"status": "error"});
}
});
});
// Recover lost password
app.post('/recover_password', function(req, res) {
var username = req.body.username.toLowerCase();
var graph = new Data.Graph(seed).connect('couch', {url: config.couchdb_url});
graph.fetch({_id: "/user/"+username}, function(err) {
var user = graph.get("/user/"+username);
if (user) {
user.set({
tan: Data.uuid()
});
graph.sync(function(err) {
// Message object
var message = {
sender: 'Substance <info@substance.io>',
to: user.get('email'),
subject: 'Reset your Substance password',
body: 'In order to reset your password on Substance, click on the link below:\n'+config.server_url+"/reset/"+user.get('username')+"/"+user.get('tan'),
debug: true
};
if (err) return res.send({"status": "error"}, 404);
// Notify
var mail = nodemailer.send_mail(message, function(err) {
if (err) return res.send({"status": "error"}, 404);
res.send({"status": "ok"});
});
});
} else {
res.send({"status": "error"}, 404);
}
});
});
// Confirm collaboration on a document
app.post('/confirm_collaborator', function(req, res) {
var tan = req.body.tan,
user = req.body.user;
var graph = new Data.Graph(seed).connect('couch', {url: config.couchdb_url});
if (req.session.username && req.session.username === user) {
graph.fetch({type: "/type/collaborator", tan: tan, "document": {}}, function(err, nodes) {
if (nodes.length <= 0) return res.send({"status": "error"});
var doc = nodes.first().get('document');
if (doc.get('creator')._id === "/user/"+user) return res.send({"status": "error", "error": "already_involved"});
graph.fetch({type: "/type/collaborator", document: doc._id, user: "/user/"+user}, function(err, collaborators) {
if (collaborators.length > 0) return res.send({"status": "error", "error": "already_involved"});
graph.get(nodes.first()._id).set({
user: "/user/"+user,
status: "confirmed"
});
graph.fetch({type: "/type/subscription", user: "/user/"+user, document: doc._id}, function(err, nodes) {
if (nodes.length === 0) {
// Add subscription
graph.set(null, {
type: "/type/subscription",
user: "/user/"+user,
document: doc._id
});
}
graph.sync(function(err) {
return err ? res.send({"status": "error"}) : res.send({"status": "ok", "graph": {}});
});
});
});
});
} else {
res.send({"status": "error", "error": "unknown_error"});
}
});
// Invite Collaborator by Email
app.post('/invite', function(req, res) {
var document = req.body.document,
email = req.body.email,
mode = req.body.mode;
if (!VALIDATE_EMAIL.test(email)) {
return res.send({"status": "error", "error": "invalid_email"});
}
var graph = new Data.Graph(seed).connect('couch', {url: config.couchdb_url});
graph.fetch({_id: document}, function(err) {
var doc = graph.get(document);
// Check if authorized — only the creator is allowed to invite collaborators
if (doc.get('creator')._id.split('/')[2] !== req.session.username) {
return res.send({"status": "error", "error": "not_authorized"});
}
graph.fetch({type: "/type/collaborator", document: document, email: email}, function(err, nodes) {
if (nodes.length>0) return res.send({"status": "error", "error": "already_invited"});
// Create collaborator object
var collaborator = graph.set({
type: "/type/collaborator",
document: document,
email: email,
tan: Data.uuid(),
mode: mode,
user: null,
status: "pending",
created_at: new Date()
});
// Message object
var message = {
sender: 'Substance <info@substance.io>',
to: email,
subject: doc.get('title'),
body: "\""+ doc.get('creator')._id.split('/')[2] + "\" invited you to collaborate on his document \""+doc.get('title')+"\" on Substance. \n\n "+ config.server_url +"/collaborate/"+collaborator.get('tan'),
// Would like you to see his document. in the view case.
debug: true
};
graph.sync(function(err) {
res.send({"status": "ok", "graph": doc.toJSON()});
if (err) return;
// Notify
var mail = nodemailer.send_mail(message, function(err) {
if(err) {
console.log('Error occured');
console.log(err.message);
return;
}
console.log('Successfully notified collaborator.');
});
});
});
});
});
app.get('/notifications', function(req, res) {
if (!req.session) return res.send({});
getNotifications(req.session.username, function(err, notifications) {
// Only deliver unread notifications
var unreadNotifications = {};
_.each(notifications, function(n, key) {
if (!n.read && _.include(n.type, "/type/notification")) {
unreadNotifications[key] = n;
unreadNotifications[n.event] = notifications[n.event];
}
});
res.send(JSON.stringify(unreadNotifications));
});
});
function fetchGravatar(username, size, res, callback) {
db.get("/user/"+username, function(err, node) {
if (err) return callback(err);
var email = node.email || "";
var host = 'www.gravatar.com';
var query = "?s="+size+"&d=retro";
var path = '/avatar/' + crypto.createHash('md5').update(email.toLowerCase()).digest('hex') + query;
http.get({host: host, path: path}, function(cres) {
if (cres.statusCode !== 200) return callback('error', '');
cres.setEncoding('binary');
cres.on('data', function(d) {
res.write(d, 'binary');
});
cres.on('end', function() {
callback(null);
});
}).on('error', function(e) {
callback(e);
});
});
}
app.get('/avatar/:username/:size', function(req, res) {
res.writeHead(200, { 'Content-Type': 'image/png'});
fetchGravatar(req.params.username, req.params.size, res, function() {
res.end();
});
});
// Increments or initializes a counter
// TODO: put into separate module
function count(counterId, callback) {
db.get(counterId, function(err, node) {
var node = node ? node : { _id: counterId, type: ["/type/counter"] };
node.value = err ? 1 : node.value + 1;
db.save(node, function(err, node) {
if (err) return callback(err);
callback(null, node.value);
});
});
}
// Creates a new version from the current document state
// TODO: check if authorized
app.post('/publish', function(req, res) {
var document = req.body.document;
var remark = req.body.remark;
var graph = new Data.Graph(seed).connect('couch', {url: config.couchdb_url});
Document.getContent(document, function(err, data, id) {
count('/counter/document/'+document.split('/')[3], function(err, versionCount) {
// Create a new version
var version = graph.set({
_id: "/version/"+document.split('/')[3]+"/"+versionCount,
type: "/type/version",
document: document,
remark: remark,
created_at: new Date(),
data: data
});
graph.sync(function(err) {
if (err) res.send({"status": "error"}, 500);
res.send({"status": "ok", "version": version._id});
});
});
});
});
// Returns a specific version of the requested doc
app.get('/documents/:username/:name/:version', function(req, res) {
Document.get(req.params.username, req.params.name, req.params.version, req.session ? req.session.username : null, function(err, graph, id, authorized, version, published) {
if (err) return res.json({status: "error", error: err});
res.json({status: "ok", graph: graph, id: id, authorized: authorized, version: version, published: published });
});
});
// Returns the latest version of the requested doc
app.get('/documents/:username/:name', function(req, res) {
Document.get(req.params.username, req.params.name, null, req.session ? req.session.username : null, function(err, graph, id, authorized, version, published) {
if (err) return res.json({status: "error", error: err});
res.json({status: "ok", graph: graph, id: id, authorized: authorized, version: version, published: published});
});
});
// Write a single document, expressed as a graph
// app.post('/writedocument', function(req, res) {
// var graph = new Data.Graph(seed, false).connect('couch', { url: config.couchdb_url, force_updates: true });
// graph.merge(JSON.parse(req.rawBody), true);
// graph.sync(function(err, nodes) {
// res.send({"status": "ok"});
// });
// });
console.log('READY: Substance is listening http://'+config['server_host']+':'+config['server_port']);
app.listen(config['server_port'], config['server_host']);