Commit e52006c2 authored by Jarrod's avatar Jarrod 💬

Normalize error responses

parent 760f5083
......@@ -16,29 +16,28 @@ module.exports = new Pluggable({
'GET /ahoy.js': { action: 'get-ahoyjs', cache: 30 },
'GET /apidoc': {
action: 'apidoc',
cache: 30
// TODO: Permission based routing stuff
cache: 30,
permission: 'admin'
},
},
async initialize () {
sails.after('lifted', () => {
sails.middleware.responses.badRequest = function badRequest (arg) {
const { req, res } = this
const message = !arg ? 'Invalid request' : _.isString(arg) ? arg : _.isObject(arg) && arg.message ? arg.message : 'Bad Request'
res.status(400).send({
error: 'E_BADREQUEST',
message
}).end()
}
sails.middleware.responses.notFound = function notFound (arg) {
const { req, res } = this
const message = !arg ? 'Resource not found' : _.isString(arg) ? arg : _.isObject(arg) && arg.message ? arg.message : 'Resource not found'
res.status(404).send({
error: 'E_NOTFOUND',
message
}).end()
// Attach custom methods to `res` object like `res.notFound('message')`
for (let mw of [
['badRequest', 400, 'E_BADREQUEST', 'Invalid Request'],
['unauthorized', 401, 'E_UNAUTHORIZED', 'Unauthorized'],
['forbidden', 403, 'E_FORBIDDEN', 'Forbidden'],
['notFound', 404, 'E_NOTFOUND', 'Resource not found'],
]) {
sails.middleware.responses[mw[0]] = function (arg) {
const { req, res } = this
const message = !arg ? mw[3] : _.isString(arg) ? arg : _.isObject(arg) && arg.message ? arg.message : mw[3]
res.status(mw[1]).send({
error: mw[2],
message
}).end()
}
}
})
},
......@@ -67,10 +66,7 @@ module.exports = new Pluggable({
after: {
'/*': {
fn: (req, res, next) => {
return res.status(400).json({
error: 'Bad Request',
message: 'Endpoint not found'
}).end()
return res.badRequest('Endpoint not found')
}
}
}
......
......@@ -11,6 +11,11 @@ module.exports = function (req, res, next) {
sails.log[logLevel](' - Permission is required: ', permission);
if (!req.me) {
sails.log[logLevel](' ❌ User is not authenticated - bailing on request');
return res.unauthorized();
}
if (req.me && User.hasPermission(req.me, User.PERMISSIONS[permission])) {
sails.log[logLevel](' ✓ User has required permission ' + permission);
return next();
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment