-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
512 lines (431 loc) · 11.7 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
// A simple server for saving plain text to files,
// and reading them again, from time to time.
var express = require('express'),
routes = require('./routes'),
http = require('http'),
path = require('path'),
fs = require('fs'),
mkdirp = require('mkdirp'),
ncp = require('ncp').ncp,
uuid = require('node-uuid'),
settings = require('./config/settings.js');
var app = module.exports = express();
var datadir = path.join(__dirname, 'data');
var statedir = path.join(__dirname, 'state');
mkdirp.sync(statedir);
var extension = '.txt';
var rootFilename = 'root';
// Windows: iisnode restarts all the time, so we'll want
// a cookie secret that doesn't change from instance to instance.
var cookieSecret = function() {
var secret;
var cookieSecretPath = path.join(statedir, 'cookieSecret');
var wasCookieCreated = false;
if (fs.existsSync(cookieSecretPath)) {
secret = fs.readFileSync(cookieSecretPath).toString();
}
else {
secret = uuid.v4();
fs.writeFileSync(cookieSecretPath, secret);
wasCookieCreated = true;
}
return {
wasCreated: wasCookieCreated,
data: secret
}
}(); // closure
// all environments
app.set('port', settings.port());
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.cookieParser(cookieSecret.data));
app.use(express.methodOverride());
app.use(app.router);
// development only
app.configure('development', function() {
app.use(express.errorHandler());
});
// production only
app.configure('production', function () {
// Copy files from ./config/notes-data to ./data
var initialNotesDataDir = path.join(__dirname, 'config', 'notes-data');
fs.exists(datadir, function (exists) {
// Only do this if there isn't a data dir already.
if (!exists) {
var options = {
clobber: false
};
ncp(initialNotesDataDir, datadir, options, function (err) {
if (err) {
console.log("Failure during initial-notes data copy.");
console.log(err);
}
});
}
});
});
//-----------------------------------------------------------
// Auth
//
var activeSessions = function () {
var sessions = {};
var sessionsPath = path.join(statedir, 'sessions.json');
// We assume that there is only one instance of Node running
// at a time. If that's true, we don't have to worry about
// multiple threads writing to the sessions file at once.
var saveSessions = function () {
fs.writeFileSync(sessionsPath, JSON.stringify(sessions))
};
var getSavedSessions = function () {
var noSessions = {};
if (fs.existsSync(sessionsPath)) {
return JSON.parse(fs.readFileSync(sessionsPath));
}
else {
return noSessions;
}
};
var getSession = function (sessionId) {
return sessions[sessionId];
};
var setSession = function (sessionId, session) {
sessions[sessionId] = session;
saveSessions();
};
var deleteSession = function (sessionId) {
delete sessions[sessionId];
saveSessions();
};
// Load our active sessions from disk on startup.
// If a new cookie secret was created, that means
// that all of our old sessions are invalid.
if (cookieSecret.wasCreated) {
sessions = {};
saveSessions();
}
else {
sessions = {};
var savedSessions = getSavedSessions();
// Only keep the sessions that haven't expired.
var now = Date.now();
for (var sessionId in savedSessions) {
if (now < savedSessions[sessionId].expires) {
sessions[sessionId] = savedSessions[sessionId];
}
}
saveSessions();
}
return {
get: getSession,
set: setSession,
'delete': deleteSession
};
}(); // closure
var cookieSessionKey = 'insecure-nonsense';
var createSessionCookie = function (req, res) {
var cookieDomain = req.host === "localhost" ? null : req.host;
var oneMinute = 60 * 1000;
var oneHour = 60 * oneMinute;
var oneDay = 24 * oneHour;
var sixMonths = 182 * oneDay;
var oneYear = 365 * oneDay;
var sessionId = uuid.v4();
var cookieOptions = {
domain: cookieDomain,
maxAge: sixMonths,
httpOnly: true,
signed: true
};
var session = {
created: Date.now(),
expires: Date.now() + cookieOptions.maxAge
};
activeSessions.set(sessionId, session);
res.cookie(cookieSessionKey, sessionId, cookieOptions);
};
var updateSessionCookie = function (sessionId, req, res) {
var session = activeSessions.get(sessionId);
var lastUsedMoreThanOneDayAgo = function (session) {
var oneDay = 24 * 60 * 60 * 1000;
return ((Date.now() - session.created) > oneDay);
}
// TODO: This may be a premature optimization.
// I clearly do not understand the performance costs
// of creating a new cookie. Why not make a new
// cookie with each request?
//
// The only reason I am doing this is because the idea
// of throwing out a cookie after one bite seems like
// a waste of cookies.
//
// Also, is rolling-cookie-auth a silly idea? I guess
// it prevents old session ids from being used, but
// once you have an active session id, you're all set
// until the server is restarted.
//
// In other words, we probably want to have a
// rolling-expiration of two months and a hard
// always-expire after something like six months,
// but frankly this is good enough for now.
if (session && lastUsedMoreThanOneDayAgo(session)) {
createSessionCookie(req, res);
// remove the old session.
activeSessions.delete(sessionId);
}
};
var isActiveSession = function (sessionId) {
return activeSessions.get(sessionId);
};
var getSessionId = function (req) {
return req.signedCookies[cookieSessionKey];
};
var permissions = function (req, res, next) {
req.permissions = {
read: true,
write: false
};
// If there's no authcode set, everyone can write.
if (!settings.authcode()) {
req.permissions.write = true;
// TODO: Probably clear active sessions, too,
// but maybe that doesn't matter since we have
// to reset the server anyway to set the authcode,
// which in turn invalidates all the cookies.
}
else {
var sessionId = getSessionId(req);
// If our cookie has expired, sessionId will be false-y,
// though this can be faked, I guess.
if (sessionId && isActiveSession(sessionId)) {
var session = activeSessions.get(sessionId);
if (session.expires > Date.now()) {
req.permissions.write = true;
updateSessionCookie(sessionId, req, res);
}
}
}
next();
};
app.post("/_/auth", function (req, res) {
var data = req.body;
var isAuthorized = function (authcode) {
if (!settings || !settings.authcode()) {
return true;
}
return settings.authcode() === authcode;
};
if (isAuthorized(data.authcode)) {
createSessionCookie(req, res);
res.send(200); // ok. cookie is content.
}
else {
res.send(401);
}
});
app.get("/_/auth-required", function (req, res) {
if (settings.authcode()) {
res.send(true);
}
else {
res.send(false);
}
});
app.get("/_/permissions", permissions, function (req, res) {
res.send(req.permissions);
res.send(200);
});
app.get("/_/signout", function (req, res) {
var sessionId = getSessionId(req);
activeSessions.delete(sessionId);
res.send(200);
});
// end Auth
//-------------------------------------------------------------------
var isRootDataFilename = function (filename) {
var rootDataFilename = path.join(datadir, rootFilename + extension);
return rootDataFilename === filename;
};
var getPathTokens = function (params) {
var path = params[0];
var tokens = path.split('/');
if (tokens[0] === '') {
tokens[0] = rootFilename;
}
return tokens;
};
var getFilePath = function (params) {
var tokens = getPathTokens(params);
var filepath = datadir;
for (var i=0; i < tokens.length; i++) {
filepath = path.join(filepath, tokens[i]);
}
// This is a simple security measure, so someone
// can't just type in, say, .htaccess and proceed
// to mess with your server. This is not intended
// to lock-in a particular format.
filepath = filepath + extension;
return filepath;
};
var getPathsInDirectory = function (dirname, callback) {
fs.exists(dirname, function (exists) {
if (!exists) {
callback([]);
}
else {
fs.readdir(dirname, function (err, files) {
if (err) {
// Not a big deal.
console.log(err);
callback([]);
}
else {
callback(files);
}
});
}
})
};
app.get('/_/notes-at/*', function (req, res) {
var notes = [];
var basename, file, dirname, isPathValid;
var filepath = getFilePath(req.params);
if (path.basename(filepath, extension) === rootFilename) {
// Special case for the root
dirname = path.dirname(filepath);
}
else {
dirname = filepath.slice(0, -extension.length);
}
getPathsInDirectory(dirname, function (files) {
// Get the names of all the notes (which end with .txt)
for (var i=0; i < files.length; i++) {
file = files[i];
// TODO: Maybe denote something as a directory in some way.
if (path.extname(file) === extension) {
basename = path.basename(file, extension);
isPathValid = (basename !== rootFilename);
}
else {
basename = path.basename(file);
isPathValid = true;
}
if (isPathValid && notes.indexOf(basename) < 0) {
notes.push(basename);
}
}
res.send(notes);
});
});
app.get('/_/data/*', function (req, res) {
var filepath = getFilePath(req.params);
fs.exists(filepath, function (exists) {
if (exists) {
res.set('Content-Type', 'text/html');
res.sendfile(filepath);
}
else {
res.send(202, "Go ahead."); // Accepted
}
});
});
// Save the note data to the path specified.
app.put('/_/data/*', permissions, function (req, res) {
if (!req.permissions.write) {
res.send(401); // unauthorized
return;
}
var data = req.body.note;
var handleCallback = function (error) {
if (error) {
console.log(error);
res.send(500);
}
else {
res.send(204); // No Content
}
};
var saveFile = function (filepath, callback) {
fs.writeFile(filepath, data, callback);
};
var deleteFile = function (filepath, callback) {
fs.unlink(filepath, function (error) {
if (error) {
callback(error);
}
else {
// If our directory is empty now, delete that too.
var deleteEmptyParentDirs = function (startpath) {
var parentDirname = path.dirname(startpath);
if (parentDirname === datadir) {
// If we get to the data directory, we're done.
callback();
}
else {
fs.readdir(parentDirname, function (error, files) {
if (error) {
console.log("Error reading a directory during delete operation: " + parentDirname);
callback(err);
}
else if (files.length === 0) {
fs.rmdir(parentDirname, function (error) {
if (error) {
callback(error);
}
else {
// recursive.
deleteEmptyParentDirs(parentDirname);
}
});
}
else {
// done.
callback();
}
});
}
};
deleteEmptyParentDirs(filepath);
}
});
};
var isDataEmpty = function (d) {
return d === "";
};
// Save or delete the file, depending on
// whether the data we get is empty.
if (data || data === "") {
var filepath = getFilePath(req.params);
fs.exists(filepath, function (exists) {
if (exists) {
if (data === "" && !isRootDataFilename(filepath)) {
deleteFile(filepath, handleCallback);
}
else {
saveFile(filepath, handleCallback);
}
}
else {
mkdirp(path.dirname(filepath), function (error) {
if (error) {
handleCallback(error);
}
else {
saveFile(filepath, handleCallback);
}
});
}
});
}
});
// The secret to bridging Angular and Express in a
// way that allows us to pass any path to the client.
app.get('*', routes.index);
/**
* Start Server
*/
http.createServer(app).listen(app.get('port'), function () {
console.log('Express server listening on port ' + app.get('port'));
});