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
|
'use strict'
// response
// external modules
var fs = require('fs')
var markdownpdf = require('markdown-pdf')
var LZString = require('lz-string')
var shortId = require('shortid')
var querystring = require('querystring')
var request = require('request')
var moment = require('moment')
// core
var config = require('./config')
var logger = require('./logger')
var models = require('./models')
var utils = require('./utils')
// public
var response = {
errorForbidden: function (res) {
responseError(res, '403', 'Forbidden', 'oh no.')
},
errorNotFound: function (res) {
responseError(res, '404', 'Not Found', 'oops.')
},
errorBadRequest: function (res) {
responseError(res, '400', 'Bad Request', 'something not right.')
},
errorInternalError: function (res) {
responseError(res, '500', 'Internal Error', 'wtf.')
},
errorServiceUnavailable: function (res) {
res.status(503).send("I'm busy right now, try again later.")
},
newNote: newNote,
showNote: showNote,
showPublishNote: showPublishNote,
showPublishSlide: showPublishSlide,
showIndex: showIndex,
noteActions: noteActions,
publishNoteActions: publishNoteActions,
publishSlideActions: publishSlideActions,
githubActions: githubActions,
gitlabActions: gitlabActions
}
function responseError (res, code, detail, msg) {
res.status(code).render(config.errorpath, {
url: config.serverurl,
title: code + ' ' + detail + ' ' + msg,
code: code,
detail: detail,
msg: msg,
useCDN: config.usecdn
})
}
function showIndex (req, res, next) {
res.render(config.indexpath, {
url: config.serverurl,
useCDN: config.usecdn,
allowAnonymous: config.allowanonymous,
allowAnonymousEdits: config.allowanonymousedits,
facebook: config.isFacebookEnable,
twitter: config.isTwitterEnable,
github: config.isGitHubEnable,
gitlab: config.isGitLabEnable,
mattermost: config.isMattermostEnable,
dropbox: config.isDropboxEnable,
google: config.isGoogleEnable,
ldap: config.isLDAPEnable,
saml: config.isSAMLEnable,
email: config.isEmailEnable,
allowemailregister: config.allowemailregister,
allowpdfexport: config.allowpdfexport,
signin: req.isAuthenticated(),
infoMessage: req.flash('info'),
errorMessage: req.flash('error')
})
}
function responseHackMD (res, note) {
var body = note.content
var extracted = models.Note.extractMeta(body)
var meta = models.Note.parseMeta(extracted.meta)
var title = models.Note.decodeTitle(note.title)
title = models.Note.generateWebTitle(meta.title || title)
res.set({
'Cache-Control': 'private', // only cache by client
'X-Robots-Tag': 'noindex, nofollow' // prevent crawling
})
res.render(config.hackmdpath, {
url: config.serverurl,
title: title,
useCDN: config.usecdn,
allowAnonymous: config.allowanonymous,
allowAnonymousEdits: config.allowanonymousedits,
facebook: config.isFacebookEnable,
twitter: config.isTwitterEnable,
github: config.isGitHubEnable,
gitlab: config.isGitLabEnable,
mattermost: config.isMattermostEnable,
dropbox: config.isDropboxEnable,
google: config.isGoogleEnable,
ldap: config.isLDAPEnable,
saml: config.isSAMLEnable,
email: config.isEmailEnable,
allowemailregister: config.allowemailregister,
allowpdfexport: config.allowpdfexport
})
}
function newNote (req, res, next) {
var owner = null
if (req.isAuthenticated()) {
owner = req.user.id
} else if (!config.allowanonymous) {
return response.errorForbidden(res)
}
models.Note.create({
ownerId: owner,
alias: req.alias ? req.alias : null,
content: req.body ? req.body : ''
}).then(function (note) {
return res.redirect(config.serverurl + '/' + LZString.compressToBase64(note.id))
}).catch(function (err) {
logger.error(err)
return response.errorInternalError(res)
})
}
function checkViewPermission (req, note) {
if (note.permission === 'private') {
if (!req.isAuthenticated() || note.ownerId !== req.user.id) { return false } else { return true }
} else if (note.permission === 'limited' || note.permission === 'protected') {
if (!req.isAuthenticated()) { return false } else { return true }
} else {
return true
}
}
function findNote (req, res, callback, include) {
var noteId = req.params.noteId
var id = req.params.noteId || req.params.shortid
models.Note.parseNoteId(id, function (err, _id) {
if (err) {
logger.log(err)
}
models.Note.findOne({
where: {
id: _id
},
include: include || null
}).then(function (note) {
if (!note) {
if (config.allowfreeurl && noteId) {
req.alias = noteId
return newNote(req, res)
} else {
return response.errorNotFound(res)
}
}
if (!checkViewPermission(req, note)) {
return response.errorForbidden(res)
} else {
return callback(note)
}
}).catch(function (err) {
logger.error(err)
return response.errorInternalError(res)
})
})
}
function showNote (req, res, next) {
findNote(req, res, function (note) {
// force to use note id
var noteId = req.params.noteId
var id = LZString.compressToBase64(note.id)
if ((note.alias && noteId !== note.alias) || (!note.alias && noteId !== id)) { return res.redirect(config.serverurl + '/' + (note.alias || id)) }
return responseHackMD(res, note)
})
}
function showPublishNote (req, res, next) {
var include = [{
model: models.User,
as: 'owner'
}, {
model: models.User,
as: 'lastchangeuser'
}]
findNote(req, res, function (note) {
// force to use short id
var shortid = req.params.shortid
if ((note.alias && shortid !== note.alias) || (!note.alias && shortid !== note.shortid)) {
return res.redirect(config.serverurl + '/s/' + (note.alias || note.shortid))
}
note.increment('viewcount').then(function (note) {
if (!note) {
return response.errorNotFound(res)
}
var body = note.content
var extracted = models.Note.extractMeta(body)
var markdown = extracted.markdown
var meta = models.Note.parseMeta(extracted.meta)
var createtime = note.createdAt
var updatetime = note.lastchangeAt
var title = models.Note.decodeTitle(note.title)
title = models.Note.generateWebTitle(meta.title || title)
var origin = config.serverurl
var data = {
title: title,
description: meta.description || (markdown ? models.Note.generateDescription(markdown) : null),
viewcount: note.viewcount,
createtime: createtime,
updatetime: updatetime,
url: origin,
body: body,
useCDN: config.usecdn,
owner: note.owner ? note.owner.id : null,
ownerprofile: note.owner ? models.User.getProfile(note.owner) : null,
lastchangeuser: note.lastchangeuser ? note.lastchangeuser.id : null,
lastchangeuserprofile: note.lastchangeuser ? models.User.getProfile(note.lastchangeuser) : null,
robots: meta.robots || false, // default allow robots
GA: meta.GA,
disqus: meta.disqus
}
return renderPublish(data, res)
}).catch(function (err) {
logger.error(err)
return response.errorInternalError(res)
})
}, include)
}
function renderPublish (data, res) {
res.set({
'Cache-Control': 'private' // only cache by client
})
res.render(config.prettypath, data)
}
function actionPublish (req, res, note) {
res.redirect(config.serverurl + '/s/' + (note.alias || note.shortid))
}
function actionSlide (req, res, note) {
res.redirect(config.serverurl + '/p/' + (note.alias || note.shortid))
}
function actionDownload (req, res, note) {
var body = note.content
var title = models.Note.decodeTitle(note.title)
var filename = title
filename = encodeURIComponent(filename)
res.set({
'Access-Control-Allow-Origin': '*', // allow CORS as API
'Access-Control-Allow-Headers': 'Range',
'Access-Control-Expose-Headers': 'Cache-Control, Content-Encoding, Content-Range',
'Content-Type': 'text/markdown; charset=UTF-8',
'Cache-Control': 'private',
'Content-disposition': 'attachment; filename=' + filename + '.md',
'X-Robots-Tag': 'noindex, nofollow' // prevent crawling
})
res.send(body)
}
function actionInfo (req, res, note) {
var body = note.content
var extracted = models.Note.extractMeta(body)
var markdown = extracted.markdown
var meta = models.Note.parseMeta(extracted.meta)
var createtime = note.createdAt
var updatetime = note.lastchangeAt
var title = models.Note.decodeTitle(note.title)
var data = {
title: meta.title || title,
description: meta.description || (markdown ? models.Note.generateDescription(markdown) : null),
viewcount: note.viewcount,
createtime: createtime,
updatetime: updatetime
}
res.set({
'Access-Control-Allow-Origin': '*', // allow CORS as API
'Access-Control-Allow-Headers': 'Range',
'Access-Control-Expose-Headers': 'Cache-Control, Content-Encoding, Content-Range',
'Cache-Control': 'private', // only cache by client
'X-Robots-Tag': 'noindex, nofollow' // prevent crawling
})
res.send(data)
}
function actionPDF (req, res, note) {
var body = note.content
var extracted = models.Note.extractMeta(body)
var title = models.Note.decodeTitle(note.title)
if (!fs.existsSync(config.tmppath)) {
fs.mkdirSync(config.tmppath)
}
var path = config.tmppath + '/' + Date.now() + '.pdf'
markdownpdf().from.string(extracted.markdown).to(path, function () {
var stream = fs.createReadStream(path)
var filename = title
// Be careful of special characters
filename = encodeURIComponent(filename)
// Ideally this should strip them
res.setHeader('Content-disposition', 'attachment; filename="' + filename + '.pdf"')
res.setHeader('Cache-Control', 'private')
res.setHeader('Content-Type', 'application/pdf; charset=UTF-8')
res.setHeader('X-Robots-Tag', 'noindex, nofollow') // prevent crawling
stream.pipe(res)
fs.unlink(path)
})
}
function actionGist (req, res, note) {
var data = {
client_id: config.github.clientID,
redirect_uri: config.serverurl + '/auth/github/callback/' + LZString.compressToBase64(note.id) + '/gist',
scope: 'gist',
state: shortId.generate()
}
var query = querystring.stringify(data)
res.redirect('https://github.com/login/oauth/authorize?' + query)
}
function actionRevision (req, res, note) {
var actionId = req.params.actionId
if (actionId) {
var time = moment(parseInt(actionId))
if (time.isValid()) {
models.Revision.getPatchedNoteRevisionByTime(note, time, function (err, content) {
if (err) {
logger.error(err)
return response.errorInternalError(res)
}
if (!content) {
return response.errorNotFound(res)
}
res.set({
'Access-Control-Allow-Origin': '*', // allow CORS as API
'Access-Control-Allow-Headers': 'Range',
'Access-Control-Expose-Headers': 'Cache-Control, Content-Encoding, Content-Range',
'Cache-Control': 'private', // only cache by client
'X-Robots-Tag': 'noindex, nofollow' // prevent crawling
})
res.send(content)
})
} else {
return response.errorNotFound(res)
}
} else {
models.Revision.getNoteRevisions(note, function (err, data) {
if (err) {
logger.error(err)
return response.errorInternalError(res)
}
var out = {
revision: data
}
res.set({
'Access-Control-Allow-Origin': '*', // allow CORS as API
'Access-Control-Allow-Headers': 'Range',
'Access-Control-Expose-Headers': 'Cache-Control, Content-Encoding, Content-Range',
'Cache-Control': 'private', // only cache by client
'X-Robots-Tag': 'noindex, nofollow' // prevent crawling
})
res.send(out)
})
}
}
function noteActions (req, res, next) {
var noteId = req.params.noteId
findNote(req, res, function (note) {
var action = req.params.action
switch (action) {
case 'publish':
case 'pretty': // pretty deprecated
actionPublish(req, res, note)
break
case 'slide':
actionSlide(req, res, note)
break
case 'download':
actionDownload(req, res, note)
break
case 'info':
actionInfo(req, res, note)
break
case 'pdf':
if (config.allowpdfexport) {
actionPDF(req, res, note)
} else {
logger.error('PDF export failed: Disabled by config. Set "allowpdfexport: true" to enable. Check the documentation for details')
response.errorForbidden(res)
}
break
case 'gist':
actionGist(req, res, note)
break
case 'revision':
actionRevision(req, res, note)
break
default:
return res.redirect(config.serverurl + '/' + noteId)
}
})
}
function publishNoteActions (req, res, next) {
findNote(req, res, function (note) {
var action = req.params.action
switch (action) {
case 'edit':
res.redirect(config.serverurl + '/' + (note.alias ? note.alias : LZString.compressToBase64(note.id)))
break
default:
res.redirect(config.serverurl + '/s/' + note.shortid)
break
}
})
}
function publishSlideActions (req, res, next) {
findNote(req, res, function (note) {
var action = req.params.action
switch (action) {
case 'edit':
res.redirect(config.serverurl + '/' + (note.alias ? note.alias : LZString.compressToBase64(note.id)))
break
default:
res.redirect(config.serverurl + '/p/' + note.shortid)
break
}
})
}
function githubActions (req, res, next) {
var noteId = req.params.noteId
findNote(req, res, function (note) {
var action = req.params.action
switch (action) {
case 'gist':
githubActionGist(req, res, note)
break
default:
res.redirect(config.serverurl + '/' + noteId)
break
}
})
}
function githubActionGist (req, res, note) {
var code = req.query.code
var state = req.query.state
if (!code || !state) {
return response.errorForbidden(res)
} else {
var data = {
client_id: config.github.clientID,
client_secret: config.github.clientSecret,
code: code,
state: state
}
var authUrl = 'https://github.com/login/oauth/access_token'
request({
url: authUrl,
method: 'POST',
json: data
}, function (error, httpResponse, body) {
if (!error && httpResponse.statusCode === 200) {
var accessToken = body.access_token
if (accessToken) {
var content = note.content
var title = models.Note.decodeTitle(note.title)
var filename = title.replace('/', ' ') + '.md'
var gist = {
'files': {}
}
gist.files[filename] = {
'content': content
}
var gistUrl = 'https://api.github.com/gists'
request({
url: gistUrl,
headers: {
'User-Agent': 'HackMD',
'Authorization': 'token ' + accessToken
},
method: 'POST',
json: gist
}, function (error, httpResponse, body) {
if (!error && httpResponse.statusCode === 201) {
res.setHeader('referer', '')
res.redirect(body.html_url)
} else {
return response.errorForbidden(res)
}
})
} else {
return response.errorForbidden(res)
}
} else {
return response.errorForbidden(res)
}
})
}
}
function gitlabActions (req, res, next) {
var noteId = req.params.noteId
findNote(req, res, function (note) {
var action = req.params.action
switch (action) {
case 'projects':
gitlabActionProjects(req, res, note)
break
default:
res.redirect(config.serverurl + '/' + noteId)
break
}
})
}
function gitlabActionProjects (req, res, note) {
if (req.isAuthenticated()) {
models.User.findOne({
where: {
id: req.user.id
}
}).then(function (user) {
if (!user) { return response.errorNotFound(res) }
var ret = { baseURL: config.gitlab.baseURL }
ret.accesstoken = user.accessToken
ret.profileid = user.profileid
request(
config.gitlab.baseURL + '/api/v3/projects?access_token=' + user.accessToken,
function (error, httpResponse, body) {
if (!error && httpResponse.statusCode === 200) {
ret.projects = JSON.parse(body)
return res.send(ret)
} else {
return res.send(ret)
}
}
)
}).catch(function (err) {
logger.error('gitlab action projects failed: ' + err)
return response.errorInternalError(res)
})
} else {
return response.errorForbidden(res)
}
}
function showPublishSlide (req, res, next) {
var include = [{
model: models.User,
as: 'owner'
}, {
model: models.User,
as: 'lastchangeuser'
}]
findNote(req, res, function (note) {
// force to use short id
var shortid = req.params.shortid
if ((note.alias && shortid !== note.alias) || (!note.alias && shortid !== note.shortid)) { return res.redirect(config.serverurl + '/p/' + (note.alias || note.shortid)) }
note.increment('viewcount').then(function (note) {
if (!note) {
return response.errorNotFound(res)
}
var body = note.content
var extracted = models.Note.extractMeta(body)
var markdown = extracted.markdown
var meta = models.Note.parseMeta(extracted.meta)
var createtime = note.createdAt
var updatetime = note.lastchangeAt
var title = models.Note.decodeTitle(note.title)
title = models.Note.generateWebTitle(meta.title || title)
var origin = config.serverurl
var data = {
title: title,
description: meta.description || (markdown ? models.Note.generateDescription(markdown) : null),
viewcount: note.viewcount,
createtime: createtime,
updatetime: updatetime,
url: origin,
body: markdown,
theme: meta.slideOptions && utils.isRevealTheme(meta.slideOptions.theme),
meta: JSON.stringify(extracted.meta),
useCDN: config.usecdn,
owner: note.owner ? note.owner.id : null,
ownerprofile: note.owner ? models.User.getProfile(note.owner) : null,
lastchangeuser: note.lastchangeuser ? note.lastchangeuser.id : null,
lastchangeuserprofile: note.lastchangeuser ? models.User.getProfile(note.lastchangeuser) : null,
robots: meta.robots || false, // default allow robots
GA: meta.GA,
disqus: meta.disqus
}
return renderPublishSlide(data, res)
}).catch(function (err) {
logger.error(err)
return response.errorInternalError(res)
})
}, include)
}
function renderPublishSlide (data, res) {
res.set({
'Cache-Control': 'private' // only cache by client
})
res.render(config.slidepath, data)
}
module.exports = response
|