CartoDB-SQL-API/lib/api/middlewares/user.js

39 lines
1.2 KiB
JavaScript
Raw Normal View History

2018-10-24 21:42:33 +08:00
'use strict';
const CdbRequest = require('../../models/cartodb-request');
2016-10-04 21:19:31 +08:00
2019-10-04 01:35:18 +08:00
module.exports = function user (metadataBackend) {
const cdbRequest = new CdbRequest();
return function userMiddleware (req, res, next) {
res.locals.user = getUserNameFromRequest(req, cdbRequest);
2019-12-24 01:19:08 +08:00
checkUserExists(metadataBackend, res.locals.user, function (err, userExists) {
if (err || !userExists) {
const error = new Error('Unauthorized');
error.type = 'auth';
error.subtype = 'user-not-found';
error.http_status = 404;
error.message = errorUserNotFoundMessageTemplate(res.locals.user);
next(error);
}
return next();
});
};
2016-10-04 21:19:31 +08:00
};
2019-10-04 01:35:18 +08:00
function getUserNameFromRequest (req, cdbRequest) {
return cdbRequest.userByReq(req);
}
2019-10-04 01:35:18 +08:00
function checkUserExists (metadataBackend, userName, callback) {
2019-12-24 01:19:08 +08:00
metadataBackend.getUserId(userName, function (err) {
callback(err, !err);
});
}
2019-10-04 01:35:18 +08:00
function errorUserNotFoundMessageTemplate (user) {
return `Sorry, we can't find CARTO user '${user}'. Please check that you have entered the correct domain.`;
}