Move note actions to their own file.

Because of circular import problems, this commit also moves the error messages from response.js to errors.js

Signed-off-by: David Mehren <dmehren1@gmail.com>
This commit is contained in:
David Mehren 2019-10-27 13:51:53 +01:00
parent 20a67e3446
commit f78540c3fb
No known key found for this signature in database
GPG key ID: 6017AF117F9756CB
16 changed files with 410 additions and 390 deletions

6
app.js
View file

@ -22,7 +22,7 @@ var flash = require('connect-flash')
// core // core
var config = require('./lib/config') var config = require('./lib/config')
var logger = require('./lib/logger') var logger = require('./lib/logger')
var response = require('./lib/response') var errors = require('./lib/errors')
var models = require('./lib/models') var models = require('./lib/models')
var csp = require('./lib/csp') var csp = require('./lib/csp')
@ -212,11 +212,11 @@ app.use(require('./lib/web/auth'))
app.use(require('./lib/web/historyRouter')) app.use(require('./lib/web/historyRouter'))
app.use(require('./lib/web/userRouter')) app.use(require('./lib/web/userRouter'))
app.use(require('./lib/web/imageRouter')) app.use(require('./lib/web/imageRouter'))
app.use(require('./lib/web/noteRouter')) app.use(require('./lib/web/note/router'))
// response not found if no any route matxches // response not found if no any route matxches
app.get('*', function (req, res) { app.get('*', function (req, res) {
response.errorNotFound(res) errors.errorNotFound(res)
}) })
// socket.io secure // socket.io secure

38
lib/errors.js Normal file
View file

@ -0,0 +1,38 @@
const config = require('./config')
module.exports = {
errorForbidden: function (res) {
const { req } = res
if (req.user) {
responseError(res, '403', 'Forbidden', 'oh no.')
} else {
req.flash('error', 'You are not allowed to access this page. Maybe try logging in?')
res.redirect(config.serverURL + '/')
}
},
errorNotFound: function (res) {
responseError(res, '404', 'Not Found', 'oops.')
},
errorBadRequest: function (res) {
responseError(res, '400', 'Bad Request', 'something not right.')
},
errorTooLong: function (res) {
responseError(res, '413', 'Payload Too Large', 'Shorten your note!')
},
errorInternalError: function (res) {
responseError(res, '500', 'Internal Error', 'wtf.')
},
errorServiceUnavailable: function (res) {
res.status(503).send('I\'m busy right now, try again later.')
}
}
function responseError (res, code, detail, msg) {
res.status(code).render('error.ejs', {
title: code + ' ' + detail + ' ' + msg,
code: code,
detail: detail,
msg: msg,
opengraph: []
})
}

View file

@ -5,8 +5,8 @@ var LZString = require('lz-string')
// core // core
var logger = require('./logger') var logger = require('./logger')
var response = require('./response')
var models = require('./models') var models = require('./models')
const errors = require('./errors')
// public // public
var History = { var History = {
@ -121,14 +121,14 @@ function parseHistoryToObject (history) {
function historyGet (req, res) { function historyGet (req, res) {
if (req.isAuthenticated()) { if (req.isAuthenticated()) {
getHistory(req.user.id, function (err, history) { getHistory(req.user.id, function (err, history) {
if (err) return response.errorInternalError(res) if (err) return errors.errorInternalError(res)
if (!history) return response.errorNotFound(res) if (!history) return errors.errorNotFound(res)
res.send({ res.send({
history: parseHistoryToArray(history) history: parseHistoryToArray(history)
}) })
}) })
} else { } else {
return response.errorForbidden(res) return errors.errorForbidden(res)
} }
} }
@ -136,40 +136,40 @@ function historyPost (req, res) {
if (req.isAuthenticated()) { if (req.isAuthenticated()) {
var noteId = req.params.noteId var noteId = req.params.noteId
if (!noteId) { if (!noteId) {
if (typeof req.body['history'] === 'undefined') return response.errorBadRequest(res) if (typeof req.body['history'] === 'undefined') return errors.errorBadRequest(res)
logger.debug(`SERVER received history from [${req.user.id}]: ${req.body.history}`) logger.debug(`SERVER received history from [${req.user.id}]: ${req.body.history}`)
try { try {
var history = JSON.parse(req.body.history) var history = JSON.parse(req.body.history)
} catch (err) { } catch (err) {
return response.errorBadRequest(res) return errors.errorBadRequest(res)
} }
if (Array.isArray(history)) { if (Array.isArray(history)) {
setHistory(req.user.id, history, function (err, count) { setHistory(req.user.id, history, function (err, count) {
if (err) return response.errorInternalError(res) if (err) return errors.errorInternalError(res)
res.end() res.end()
}) })
} else { } else {
return response.errorBadRequest(res) return errors.errorBadRequest(res)
} }
} else { } else {
if (typeof req.body['pinned'] === 'undefined') return response.errorBadRequest(res) if (typeof req.body['pinned'] === 'undefined') return errors.errorBadRequest(res)
getHistory(req.user.id, function (err, history) { getHistory(req.user.id, function (err, history) {
if (err) return response.errorInternalError(res) if (err) return errors.errorInternalError(res)
if (!history) return response.errorNotFound(res) if (!history) return errors.errorNotFound(res)
if (!history[noteId]) return response.errorNotFound(res) if (!history[noteId]) return errors.errorNotFound(res)
if (req.body.pinned === 'true' || req.body.pinned === 'false') { if (req.body.pinned === 'true' || req.body.pinned === 'false') {
history[noteId].pinned = (req.body.pinned === 'true') history[noteId].pinned = (req.body.pinned === 'true')
setHistory(req.user.id, history, function (err, count) { setHistory(req.user.id, history, function (err, count) {
if (err) return response.errorInternalError(res) if (err) return errors.errorInternalError(res)
res.end() res.end()
}) })
} else { } else {
return response.errorBadRequest(res) return errors.errorBadRequest(res)
} }
}) })
} }
} else { } else {
return response.errorForbidden(res) return errors.errorForbidden(res)
} }
} }
@ -178,22 +178,22 @@ function historyDelete (req, res) {
var noteId = req.params.noteId var noteId = req.params.noteId
if (!noteId) { if (!noteId) {
setHistory(req.user.id, [], function (err, count) { setHistory(req.user.id, [], function (err, count) {
if (err) return response.errorInternalError(res) if (err) return errors.errorInternalError(res)
res.end() res.end()
}) })
} else { } else {
getHistory(req.user.id, function (err, history) { getHistory(req.user.id, function (err, history) {
if (err) return response.errorInternalError(res) if (err) return errors.errorInternalError(res)
if (!history) return response.errorNotFound(res) if (!history) return errors.errorNotFound(res)
delete history[noteId] delete history[noteId]
setHistory(req.user.id, history, function (err, count) { setHistory(req.user.id, history, function (err, count) {
if (err) return response.errorInternalError(res) if (err) return errors.errorInternalError(res)
res.end() res.end()
}) })
}) })
} }
} else { } else {
return response.errorForbidden(res) return errors.errorForbidden(res)
} }
} }

View file

@ -3,49 +3,22 @@
// external modules // external modules
var fs = require('fs') var fs = require('fs')
var path = require('path') var path = require('path')
var markdownpdf = require('markdown-pdf')
var shortId = require('shortid')
var querystring = require('querystring')
var request = require('request') var request = require('request')
var moment = require('moment')
// core // core
var config = require('./config') var config = require('./config')
var logger = require('./logger') var logger = require('./logger')
var models = require('./models') var models = require('./models')
var utils = require('./utils') var utils = require('./utils')
const noteUtil = require('./web/note/util')
const noteActions = require('./web/note/actions')
const errors = require('./errors')
// public // public
var response = { var response = {
errorForbidden: function (res) {
const { req } = res
if (req.user) {
responseError(res, '403', 'Forbidden', 'oh no.')
} else {
req.flash('error', 'You are not allowed to access this page. Maybe try logging in?')
res.redirect(config.serverURL + '/')
}
},
errorNotFound: function (res) {
responseError(res, '404', 'Not Found', 'oops.')
},
errorBadRequest: function (res) {
responseError(res, '400', 'Bad Request', 'something not right.')
},
errorTooLong: function (res) {
responseError(res, '413', 'Payload Too Large', 'Shorten your note!')
},
errorInternalError: function (res) {
responseError(res, '500', 'Internal Error', 'wtf.')
},
errorServiceUnavailable: function (res) {
res.status(503).send("I'm busy right now, try again later.")
},
showNote: showNote, showNote: showNote,
showPublishNote: showPublishNote, showPublishNote: showPublishNote,
showPublishSlide: showPublishSlide, showPublishSlide: showPublishSlide,
showIndex: showIndex, showIndex: showIndex,
noteActions: noteActions,
postNote: postNote, postNote: postNote,
publishNoteActions: publishNoteActions, publishNoteActions: publishNoteActions,
publishSlideActions: publishSlideActions, publishSlideActions: publishSlideActions,
@ -53,16 +26,6 @@ var response = {
gitlabActions: gitlabActions gitlabActions: gitlabActions
} }
function responseError (res, code, detail, msg) {
res.status(code).render('error.ejs', {
title: code + ' ' + detail + ' ' + msg,
code: code,
detail: detail,
msg: msg,
opengraph: []
})
}
function showIndex (req, res, next) { function showIndex (req, res, next) {
var authStatus = req.isAuthenticated() var authStatus = req.isAuthenticated()
var deleteToken = '' var deleteToken = ''
@ -113,79 +76,16 @@ function responseCodiMD (res, note) {
function postNote (req, res, next) { function postNote (req, res, next) {
var body = '' var body = ''
if (req.body && req.body.length > config.documentMaxLength) { if (req.body && req.body.length > config.documentMaxLength) {
return response.errorTooLong(res) return errors.errorTooLong(res)
} else if (req.body) { } else if (req.body) {
body = req.body body = req.body
} }
body = body.replace(/[\r]/g, '') body = body.replace(/[\r]/g, '')
return newNote(req, res, body) return noteUtil.newNote(req, res, body)
}
function newNote (req, res, body) {
var owner = null
var noteId = req.params.noteId ? req.params.noteId : null
if (req.isAuthenticated()) {
owner = req.user.id
} else if (!config.allowAnonymous) {
return response.errorForbidden(res)
}
if (config.allowFreeURL && noteId && !config.forbiddenNoteIDs.includes(noteId)) {
req.alias = noteId
} else if (noteId) {
return req.method === 'POST' ? response.errorForbidden(res) : response.errorNotFound(res)
}
models.Note.create({
ownerId: owner,
alias: req.alias ? req.alias : null,
content: body
}).then(function (note) {
return res.redirect(config.serverURL + '/' + (note.alias ? note.alias : models.Note.encodeNoteId(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 id = req.params.noteId || req.params.shortid
models.Note.parseNoteId(id, function (err, _id) {
if (err) {
logger.error(err)
return response.errorInternalError(res)
}
models.Note.findOne({
where: {
id: _id
},
include: include || null
}).then(function (note) {
if (!note) {
return newNote(req, res, null)
}
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) { function showNote (req, res, next) {
findNote(req, res, function (note) { noteUtil.findNote(req, res, function (note) {
// force to use note id // force to use note id
var noteId = req.params.noteId var noteId = req.params.noteId
var id = models.Note.encodeNoteId(note.id) var id = models.Note.encodeNoteId(note.id)
@ -202,7 +102,7 @@ function showPublishNote (req, res, next) {
model: models.User, model: models.User,
as: 'lastchangeuser' as: 'lastchangeuser'
}] }]
findNote(req, res, function (note) { noteUtil.findNote(req, res, function (note) {
// force to use short id // force to use short id
var shortid = req.params.shortid var shortid = req.params.shortid
if ((note.alias && shortid !== note.alias) || (!note.alias && shortid !== note.shortid)) { if ((note.alias && shortid !== note.alias) || (!note.alias && shortid !== note.shortid)) {
@ -210,7 +110,7 @@ function showPublishNote (req, res, next) {
} }
note.increment('viewcount').then(function (note) { note.increment('viewcount').then(function (note) {
if (!note) { if (!note) {
return response.errorNotFound(res) return errors.errorNotFound(res)
} }
var body = note.content var body = note.content
var extracted = models.Note.extractMeta(body) var extracted = models.Note.extractMeta(body)
@ -242,7 +142,7 @@ function showPublishNote (req, res, next) {
return renderPublish(data, res) return renderPublish(data, res)
}).catch(function (err) { }).catch(function (err) {
logger.error(err) logger.error(err)
return response.errorInternalError(res) return errors.errorInternalError(res)
}) })
}, include) }, include)
} }
@ -254,188 +154,12 @@ function renderPublish (data, res) {
res.render('pretty.ejs', data) res.render('pretty.ejs', 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 url = config.serverURL || 'http://' + req.get('host')
var body = note.content
var extracted = models.Note.extractMeta(body)
var content = extracted.markdown
var title = models.Note.decodeTitle(note.title)
if (!fs.existsSync(config.tmpPath)) {
fs.mkdirSync(config.tmpPath)
}
var path = config.tmpPath + '/' + Date.now() + '.pdf'
content = content.replace(/\]\(\//g, '](' + url + '/')
markdownpdf().from.string(content).to(path, function () {
if (!fs.existsSync(path)) {
logger.error('PDF seems to not be generated as expected. File doesn\'t exist: ' + path)
return response.errorInternalError(res)
}
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.unlinkSync(path)
})
}
function actionGist (req, res, note) {
var data = {
client_id: config.github.clientID,
redirect_uri: config.serverURL + '/auth/github/callback/' + models.Note.encodeNoteId(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) { function publishNoteActions (req, res, next) {
findNote(req, res, function (note) { noteUtil.findNote(req, res, function (note) {
var action = req.params.action var action = req.params.action
switch (action) { switch (action) {
case 'download': case 'download':
actionDownload(req, res, note) noteActions.actionDownload(req, res, note)
break break
case 'edit': case 'edit':
res.redirect(config.serverURL + '/' + (note.alias ? note.alias : models.Note.encodeNoteId(note.id)) + '?both') res.redirect(config.serverURL + '/' + (note.alias ? note.alias : models.Note.encodeNoteId(note.id)) + '?both')
@ -448,7 +172,7 @@ function publishNoteActions (req, res, next) {
} }
function publishSlideActions (req, res, next) { function publishSlideActions (req, res, next) {
findNote(req, res, function (note) { noteUtil.findNote(req, res, function (note) {
var action = req.params.action var action = req.params.action
switch (action) { switch (action) {
case 'edit': case 'edit':
@ -463,7 +187,7 @@ function publishSlideActions (req, res, next) {
function githubActions (req, res, next) { function githubActions (req, res, next) {
var noteId = req.params.noteId var noteId = req.params.noteId
findNote(req, res, function (note) { noteUtil.findNote(req, res, function (note) {
var action = req.params.action var action = req.params.action
switch (action) { switch (action) {
case 'gist': case 'gist':
@ -480,7 +204,7 @@ function githubActionGist (req, res, note) {
var code = req.query.code var code = req.query.code
var state = req.query.state var state = req.query.state
if (!code || !state) { if (!code || !state) {
return response.errorForbidden(res) return errors.errorForbidden(res)
} else { } else {
var data = { var data = {
client_id: config.github.clientID, client_id: config.github.clientID,
@ -520,14 +244,14 @@ function githubActionGist (req, res, note) {
res.setHeader('referer', '') res.setHeader('referer', '')
res.redirect(body.html_url) res.redirect(body.html_url)
} else { } else {
return response.errorForbidden(res) return errors.errorForbidden(res)
} }
}) })
} else { } else {
return response.errorForbidden(res) return errors.errorForbidden(res)
} }
} else { } else {
return response.errorForbidden(res) return errors.errorForbidden(res)
} }
}) })
} }
@ -535,7 +259,7 @@ function githubActionGist (req, res, note) {
function gitlabActions (req, res, next) { function gitlabActions (req, res, next) {
var noteId = req.params.noteId var noteId = req.params.noteId
findNote(req, res, function (note) { noteUtil.findNote(req, res, function (note) {
var action = req.params.action var action = req.params.action
switch (action) { switch (action) {
case 'projects': case 'projects':
@ -555,7 +279,7 @@ function gitlabActionProjects (req, res, note) {
id: req.user.id id: req.user.id
} }
}).then(function (user) { }).then(function (user) {
if (!user) { return response.errorNotFound(res) } if (!user) { return errors.errorNotFound(res) }
var ret = { baseURL: config.gitlab.baseURL, version: config.gitlab.version } var ret = { baseURL: config.gitlab.baseURL, version: config.gitlab.version }
ret.accesstoken = user.accessToken ret.accesstoken = user.accessToken
ret.profileid = user.profileid ret.profileid = user.profileid
@ -572,10 +296,10 @@ function gitlabActionProjects (req, res, note) {
) )
}).catch(function (err) { }).catch(function (err) {
logger.error('gitlab action projects failed: ' + err) logger.error('gitlab action projects failed: ' + err)
return response.errorInternalError(res) return errors.errorInternalError(res)
}) })
} else { } else {
return response.errorForbidden(res) return errors.errorForbidden(res)
} }
} }
@ -587,13 +311,13 @@ function showPublishSlide (req, res, next) {
model: models.User, model: models.User,
as: 'lastchangeuser' as: 'lastchangeuser'
}] }]
findNote(req, res, function (note) { noteUtil.findNote(req, res, function (note) {
// force to use short id // force to use short id
var shortid = req.params.shortid 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)) } 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) { note.increment('viewcount').then(function (note) {
if (!note) { if (!note) {
return response.errorNotFound(res) return errors.errorNotFound(res)
} }
var body = note.content var body = note.content
var extracted = models.Note.extractMeta(body) var extracted = models.Note.extractMeta(body)
@ -625,7 +349,7 @@ function showPublishSlide (req, res, next) {
return renderPublishSlide(data, res) return renderPublishSlide(data, res)
}).catch(function (err) { }).catch(function (err) {
logger.error(err) logger.error(err)
return response.errorInternalError(res) return errors.errorInternalError(res)
}) })
}, include) }, include)
} }

View file

@ -9,7 +9,7 @@ const models = require('../../../models')
const logger = require('../../../logger') const logger = require('../../../logger')
const { setReturnToFromReferer } = require('../utils') const { setReturnToFromReferer } = require('../utils')
const { urlencodedParser } = require('../../utils') const { urlencodedParser } = require('../../utils')
const response = require('../../../response') const errors = require('../../../errors')
let emailAuth = module.exports = Router() let emailAuth = module.exports = Router()
@ -39,8 +39,8 @@ passport.use(new LocalStrategy({
if (config.allowEmailRegister) { if (config.allowEmailRegister) {
emailAuth.post('/register', urlencodedParser, function (req, res, next) { emailAuth.post('/register', urlencodedParser, function (req, res, next) {
if (!req.body.email || !req.body.password) return response.errorBadRequest(res) if (!req.body.email || !req.body.password) return errors.errorBadRequest(res)
if (!validator.isEmail(req.body.email)) return response.errorBadRequest(res) if (!validator.isEmail(req.body.email)) return errors.errorBadRequest(res)
models.User.findOrCreate({ models.User.findOrCreate({
where: { where: {
email: req.body.email email: req.body.email
@ -63,14 +63,14 @@ if (config.allowEmailRegister) {
return res.redirect(config.serverURL + '/') return res.redirect(config.serverURL + '/')
}).catch(function (err) { }).catch(function (err) {
logger.error('auth callback failed: ' + err) logger.error('auth callback failed: ' + err)
return response.errorInternalError(res) return errors.errorInternalError(res)
}) })
}) })
} }
emailAuth.post('/login', urlencodedParser, function (req, res, next) { emailAuth.post('/login', urlencodedParser, function (req, res, next) {
if (!req.body.email || !req.body.password) return response.errorBadRequest(res) if (!req.body.email || !req.body.password) return errors.errorBadRequest(res)
if (!validator.isEmail(req.body.email)) return response.errorBadRequest(res) if (!validator.isEmail(req.body.email)) return errors.errorBadRequest(res)
setReturnToFromReferer(req) setReturnToFromReferer(req)
passport.authenticate('local', { passport.authenticate('local', {
successReturnToOrRedirect: config.serverURL + '/', successReturnToOrRedirect: config.serverURL + '/',

View file

@ -8,7 +8,7 @@ const models = require('../../../models')
const logger = require('../../../logger') const logger = require('../../../logger')
const { setReturnToFromReferer } = require('../utils') const { setReturnToFromReferer } = require('../utils')
const { urlencodedParser } = require('../../utils') const { urlencodedParser } = require('../../utils')
const response = require('../../../response') const errors = require('../../../errors')
let ldapAuth = module.exports = Router() let ldapAuth = module.exports = Router()
@ -81,7 +81,7 @@ passport.use(new LDAPStrategy({
})) }))
ldapAuth.post('/auth/ldap', urlencodedParser, function (req, res, next) { ldapAuth.post('/auth/ldap', urlencodedParser, function (req, res, next) {
if (!req.body.username || !req.body.password) return response.errorBadRequest(res) if (!req.body.username || !req.body.password) return errors.errorBadRequest(res)
setReturnToFromReferer(req) setReturnToFromReferer(req)
passport.authenticate('ldapauth', { passport.authenticate('ldapauth', {
successReturnToOrRedirect: config.serverURL + '/', successReturnToOrRedirect: config.serverURL + '/',

View file

@ -6,17 +6,19 @@ const response = require('../response')
const baseRouter = module.exports = Router() const baseRouter = module.exports = Router()
const errors = require('../errors')
// get index // get index
baseRouter.get('/', response.showIndex) baseRouter.get('/', response.showIndex)
// get 403 forbidden // get 403 forbidden
baseRouter.get('/403', function (req, res) { baseRouter.get('/403', function (req, res) {
response.errorForbidden(res) errors.errorForbidden(res)
}) })
// get 404 not found // get 404 not found
baseRouter.get('/404', function (req, res) { baseRouter.get('/404', function (req, res) {
response.errorNotFound(res) errors.errorNotFound(res)
}) })
// get 500 internal error // get 500 internal error
baseRouter.get('/500', function (req, res) { baseRouter.get('/500', function (req, res) {
response.errorInternalError(res) errors.errorInternalError(res)
}) })

View file

@ -5,7 +5,7 @@ const formidable = require('formidable')
const config = require('../../config') const config = require('../../config')
const logger = require('../../logger') const logger = require('../../logger')
const response = require('../../response') const errors = require('../../errors')
const imageRouter = module.exports = Router() const imageRouter = module.exports = Router()
@ -22,7 +22,7 @@ imageRouter.post('/uploadimage', function (req, res) {
form.parse(req, function (err, fields, files) { form.parse(req, function (err, fields, files) {
if (err || !files.image || !files.image.path) { if (err || !files.image || !files.image.path) {
logger.error(`formidable error: ${err}`) logger.error(`formidable error: ${err}`)
response.errorForbidden(res) errors.errorForbidden(res)
} else { } else {
logger.debug(`SERVER received uploadimage: ${JSON.stringify(files.image)}`) logger.debug(`SERVER received uploadimage: ${JSON.stringify(files.image)}`)

View file

@ -1,14 +1,14 @@
'use strict' 'use strict'
const logger = require('../../logger') const logger = require('../../logger')
const response = require('../../response') const errors = require('../../errors')
module.exports = function (req, res, next) { module.exports = function (req, res, next) {
try { try {
decodeURIComponent(req.path) decodeURIComponent(req.path)
} catch (err) { } catch (err) {
logger.error(err) logger.error(err)
return response.errorBadRequest(res) return errors.errorBadRequest(res)
} }
next() next()
} }

View file

@ -2,14 +2,14 @@
const toobusy = require('toobusy-js') const toobusy = require('toobusy-js')
const response = require('../../response') const errors = require('../../errors')
const config = require('../../config') const config = require('../../config')
toobusy.maxLag(config.tooBusyLag) toobusy.maxLag(config.tooBusyLag)
module.exports = function (req, res, next) { module.exports = function (req, res, next) {
if (toobusy()) { if (toobusy()) {
response.errorServiceUnavailable(res) errors.errorServiceUnavailable(res)
} else { } else {
next() next()
} }

187
lib/web/note/actions.js Normal file
View file

@ -0,0 +1,187 @@
'use strict'
const models = require('../../models')
const logger = require('../../logger')
const config = require('../../config')
const error = require('../../errors')
const fs = require('fs')
const shortId = require('shortid')
const markdownpdf = require('markdown-pdf')
const moment = require('moment')
const querystring = require('querystring')
const noteUtil = require('./util')
exports.doAction = function (req, res, next) {
const noteId = req.params.noteId
noteUtil.findNote(req, res, function (note) {
const 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':
exports.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')
error.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 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))
}
exports.actionDownload = function (req, res, note) {
const body = note.content
let filename = models.Note.decodeTitle(note.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) {
const body = note.content
const extracted = models.Note.extractMeta(body)
const markdown = extracted.markdown
const meta = models.Note.parseMeta(extracted.meta)
const createtime = note.createdAt
const updatetime = note.lastchangeAt
const title = models.Note.decodeTitle(note.title)
const 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) {
const url = config.serverURL || 'http://' + req.get('host')
const body = note.content
const extracted = models.Note.extractMeta(body)
let content = extracted.markdown
const title = models.Note.decodeTitle(note.title)
if (!fs.existsSync(config.tmpPath)) {
fs.mkdirSync(config.tmpPath)
}
const path = config.tmpPath + '/' + Date.now() + '.pdf'
content = content.replace(/\]\(\//g, '](' + url + '/')
markdownpdf().from.string(content).to(path, function () {
if (!fs.existsSync(path)) {
logger.error('PDF seems to not be generated as expected. File doesn\'t exist: ' + path)
return error.errorInternalError(res)
}
const stream = fs.createReadStream(path)
let 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.unlinkSync(path)
})
}
function actionGist (req, res, note) {
const data = {
client_id: config.github.clientID,
redirect_uri: config.serverURL + '/auth/github/callback/' + models.Note.encodeNoteId(note.id) + '/gist',
scope: 'gist',
state: shortId.generate()
}
const query = querystring.stringify(data)
res.redirect('https://github.com/login/oauth/authorize?' + query)
}
function actionRevision (req, res, note) {
const actionId = req.params.actionId
if (actionId) {
const time = moment(parseInt(actionId))
if (time.isValid()) {
models.Revision.getPatchedNoteRevisionByTime(note, time, function (err, content) {
if (err) {
logger.error(err)
return error.errorInternalError(res)
}
if (!content) {
return error.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 error.errorNotFound(res)
}
} else {
models.Revision.getNoteRevisions(note, function (err, data) {
if (err) {
logger.error(err)
return error.errorInternalError(res)
}
const 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)
})
}
}

32
lib/web/note/router.js Normal file
View file

@ -0,0 +1,32 @@
'use strict'
const Router = require('express').Router
const response = require('../../response')
const { markdownParser } = require('../utils')
const router = module.exports = Router()
const noteActions = require('./actions')
// get new note
router.get('/new', response.postNote)
// post new note with content
router.post('/new', markdownParser, response.postNote)
// post new note with content and alias
router.post('/new/:noteId', markdownParser, response.postNote)
// get publish note
router.get('/s/:shortid', response.showPublishNote)
// publish note actions
router.get('/s/:shortid/:action', response.publishNoteActions)
// get publish slide
router.get('/p/:shortid', response.showPublishSlide)
// publish slide actions
router.get('/p/:shortid/:action', response.publishSlideActions)
// get note by id
router.get('/:noteId', response.showNote)
// note actions
router.get('/:noteId/:action', noteActions.doAction)
// note actions with action id
router.get('/:noteId/:action/:actionId', noteActions.doAction)

67
lib/web/note/util.js Normal file
View file

@ -0,0 +1,67 @@
const models = require('../../models')
const logger = require('../../logger')
const config = require('../../config')
const errors = require('../../errors')
exports.findNote = function (req, res, callback, include) {
const id = req.params.noteId || req.params.shortid
models.Note.parseNoteId(id, function (err, _id) {
if (err) {
logger.error(err)
return errors.errorInternalError(res)
}
models.Note.findOne({
where: {
id: _id
},
include: include || null
}).then(function (note) {
if (!note) {
return exports.newNote(req, res, null)
}
if (!exports.checkViewPermission(req, note)) {
return errors.errorForbidden(res)
} else {
return callback(note)
}
}).catch(function (err) {
logger.error(err)
return errors.errorInternalError(res)
})
})
}
exports.checkViewPermission = function (req, note) {
if (note.permission === 'private') {
return !(!req.isAuthenticated() || note.ownerId !== req.user.id)
} else if (note.permission === 'limited' || note.permission === 'protected') {
return req.isAuthenticated()
} else {
return true
}
}
exports.newNote = function (req, res, body) {
let owner = null
const noteId = req.params.noteId ? req.params.noteId : null
if (req.isAuthenticated()) {
owner = req.user.id
} else if (!config.allowAnonymous) {
return errors.errorForbidden(res)
}
if (config.allowFreeURL && noteId && !config.forbiddenNoteIDs.includes(noteId)) {
req.alias = noteId
} else if (noteId) {
return req.method === 'POST' ? errors.errorForbidden(res) : errors.errorNotFound(res)
}
models.Note.create({
ownerId: owner,
alias: req.alias ? req.alias : null,
content: body
}).then(function (note) {
return res.redirect(config.serverURL + '/' + (note.alias ? note.alias : models.Note.encodeNoteId(note.id)))
}).catch(function (err) {
logger.error(err)
return errors.errorInternalError(res)
})
}

View file

@ -1,30 +0,0 @@
'use strict'
const Router = require('express').Router
const response = require('../response')
const { markdownParser } = require('./utils')
const noteRouter = module.exports = Router()
// get new note
noteRouter.get('/new', response.postNote)
// post new note with content
noteRouter.post('/new', markdownParser, response.postNote)
// post new note with content and alias
noteRouter.post('/new/:noteId', markdownParser, response.postNote)
// get publish note
noteRouter.get('/s/:shortid', response.showPublishNote)
// publish note actions
noteRouter.get('/s/:shortid/:action', response.publishNoteActions)
// get publish slide
noteRouter.get('/p/:shortid', response.showPublishSlide)
// publish slide actions
noteRouter.get('/p/:shortid/:action', response.publishSlideActions)
// get note by id
noteRouter.get('/:noteId', response.showNote)
// note actions
noteRouter.get('/:noteId/:action', response.noteActions)
// note actions with action id
noteRouter.get('/:noteId/:action/:actionId', response.noteActions)

View file

@ -2,7 +2,7 @@
const Router = require('express').Router const Router = require('express').Router
const response = require('../response') const errors = require('../errors')
const realtime = require('../realtime') const realtime = require('../realtime')
const config = require('../config') const config = require('../config')
const models = require('../models') const models = require('../models')
@ -27,11 +27,11 @@ statusRouter.get('/status', function (req, res, next) {
statusRouter.get('/temp', function (req, res) { statusRouter.get('/temp', function (req, res) {
var host = req.get('host') var host = req.get('host')
if (config.allowOrigin.indexOf(host) === -1) { if (config.allowOrigin.indexOf(host) === -1) {
response.errorForbidden(res) errors.errorForbidden(res)
} else { } else {
var tempid = req.query.tempid var tempid = req.query.tempid
if (!tempid) { if (!tempid) {
response.errorForbidden(res) errors.errorForbidden(res)
} else { } else {
models.Temp.findOne({ models.Temp.findOne({
where: { where: {
@ -39,7 +39,7 @@ statusRouter.get('/temp', function (req, res) {
} }
}).then(function (temp) { }).then(function (temp) {
if (!temp) { if (!temp) {
response.errorNotFound(res) errors.errorNotFound(res)
} else { } else {
res.header('Access-Control-Allow-Origin', '*') res.header('Access-Control-Allow-Origin', '*')
res.send({ res.send({
@ -53,7 +53,7 @@ statusRouter.get('/temp', function (req, res) {
} }
}).catch(function (err) { }).catch(function (err) {
logger.error(err) logger.error(err)
return response.errorInternalError(res) return errors.errorInternalError(res)
}) })
} }
} }
@ -62,11 +62,11 @@ statusRouter.get('/temp', function (req, res) {
statusRouter.post('/temp', urlencodedParser, function (req, res) { statusRouter.post('/temp', urlencodedParser, function (req, res) {
var host = req.get('host') var host = req.get('host')
if (config.allowOrigin.indexOf(host) === -1) { if (config.allowOrigin.indexOf(host) === -1) {
response.errorForbidden(res) errors.errorForbidden(res)
} else { } else {
var data = req.body.data var data = req.body.data
if (!data) { if (!data) {
response.errorForbidden(res) errors.errorForbidden(res)
} else { } else {
logger.debug(`SERVER received temp from [${host}]: ${req.body.data}`) logger.debug(`SERVER received temp from [${host}]: ${req.body.data}`)
models.Temp.create({ models.Temp.create({
@ -79,11 +79,11 @@ statusRouter.post('/temp', urlencodedParser, function (req, res) {
id: temp.id id: temp.id
}) })
} else { } else {
response.errorInternalError(res) errors.errorInternalError(res)
} }
}).catch(function (err) { }).catch(function (err) {
logger.error(err) logger.error(err)
return response.errorInternalError(res) return errors.errorInternalError(res)
}) })
} }
} }

View file

@ -4,7 +4,7 @@ const archiver = require('archiver')
const async = require('async') const async = require('async')
const Router = require('express').Router const Router = require('express').Router
const response = require('../response') const errors = require('../errors')
const config = require('../config') const config = require('../config')
const models = require('../models') const models = require('../models')
const logger = require('../logger') const logger = require('../logger')
@ -20,7 +20,7 @@ UserRouter.get('/me', function (req, res) {
id: req.user.id id: req.user.id
} }
}).then(function (user) { }).then(function (user) {
if (!user) { return response.errorNotFound(res) } if (!user) { return errors.errorNotFound(res) }
var profile = models.User.getProfile(user) var profile = models.User.getProfile(user)
res.send({ res.send({
status: 'ok', status: 'ok',
@ -30,7 +30,7 @@ UserRouter.get('/me', function (req, res) {
}) })
}).catch(function (err) { }).catch(function (err) {
logger.error('read me failed: ' + err) logger.error('read me failed: ' + err)
return response.errorInternalError(res) return errors.errorInternalError(res)
}) })
} else { } else {
res.send({ res.send({
@ -48,21 +48,21 @@ UserRouter.get('/me/delete/:token?', function (req, res) {
} }
}).then(function (user) { }).then(function (user) {
if (!user) { if (!user) {
return response.errorNotFound(res) return errors.errorNotFound(res)
} }
if (user.deleteToken === req.params.token) { if (user.deleteToken === req.params.token) {
user.destroy().then(function () { user.destroy().then(function () {
res.redirect(config.serverURL + '/') res.redirect(config.serverURL + '/')
}) })
} else { } else {
return response.errorForbidden(res) return errors.errorForbidden(res)
} }
}).catch(function (err) { }).catch(function (err) {
logger.error('delete user failed: ' + err) logger.error('delete user failed: ' + err)
return response.errorInternalError(res) return errors.errorInternalError(res)
}) })
} else { } else {
return response.errorForbidden(res) return errors.errorForbidden(res)
} }
}) })
@ -78,7 +78,7 @@ UserRouter.get('/me/export', function (req, res) {
archive.pipe(res) archive.pipe(res)
archive.on('error', function (err) { archive.on('error', function (err) {
logger.error('export user data failed: ' + err) logger.error('export user data failed: ' + err)
return response.errorInternalError(res) return errors.errorInternalError(res)
}) })
models.User.findOne({ models.User.findOne({
where: { where: {
@ -107,7 +107,7 @@ UserRouter.get('/me/export', function (req, res) {
callback(null, null) callback(null, null)
}, function (err) { }, function (err) {
if (err) { if (err) {
return response.errorInternalError(res) return errors.errorInternalError(res)
} }
archive.finalize() archive.finalize()
@ -115,10 +115,10 @@ UserRouter.get('/me/export', function (req, res) {
}) })
}).catch(function (err) { }).catch(function (err) {
logger.error('export user data failed: ' + err) logger.error('export user data failed: ' + err)
return response.errorInternalError(res) return errors.errorInternalError(res)
}) })
} else { } else {
return response.errorForbidden(res) return errors.errorForbidden(res)
} }
}) })