2018-10-24 21:42:33 +08:00
|
|
|
'use strict';
|
|
|
|
|
2019-10-04 00:24:39 +08:00
|
|
|
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) {
|
2018-02-17 01:21:06 +08:00
|
|
|
const cdbRequest = new CdbRequest();
|
|
|
|
|
|
|
|
return function userMiddleware (req, res, next) {
|
2020-06-30 23:42:59 +08:00
|
|
|
const { logger } = res.locals;
|
2018-05-29 19:23:50 +08:00
|
|
|
|
2020-06-30 23:42:59 +08:00
|
|
|
try {
|
|
|
|
res.locals.user = getUserNameFromRequest(req, cdbRequest);
|
|
|
|
logger.info({ user: res.locals.user });
|
|
|
|
} catch (err) {
|
|
|
|
return next(err);
|
|
|
|
}
|
|
|
|
|
|
|
|
metadataBackend.getUserId(res.locals.user, (err, userId) => {
|
2020-02-27 00:19:07 +08:00
|
|
|
if (err || !userId) {
|
2018-05-29 19:23:50 +08:00
|
|
|
const error = new Error('Unauthorized');
|
|
|
|
error.type = 'auth';
|
|
|
|
error.subtype = 'user-not-found';
|
|
|
|
error.http_status = 404;
|
|
|
|
error.message = errorUserNotFoundMessageTemplate(res.locals.user);
|
2020-06-30 23:42:59 +08:00
|
|
|
|
|
|
|
return next(error);
|
2018-05-29 19:23:50 +08:00
|
|
|
}
|
2018-06-06 21:48:22 +08:00
|
|
|
|
2020-02-27 00:19:07 +08:00
|
|
|
res.locals.userId = userId;
|
2020-06-22 15:47:22 +08:00
|
|
|
res.set('Carto-User-Id', `${userId}`);
|
2018-06-06 21:48:22 +08:00
|
|
|
return next();
|
2018-05-29 19:23:50 +08:00
|
|
|
});
|
2018-02-17 01:21:06 +08:00
|
|
|
};
|
2016-10-04 21:19:31 +08:00
|
|
|
};
|
2018-05-29 19:23:50 +08:00
|
|
|
|
2019-10-04 01:35:18 +08:00
|
|
|
function getUserNameFromRequest (req, cdbRequest) {
|
2018-05-29 19:23:50 +08:00
|
|
|
return cdbRequest.userByReq(req);
|
|
|
|
}
|
|
|
|
|
2019-10-04 01:35:18 +08:00
|
|
|
function errorUserNotFoundMessageTemplate (user) {
|
2018-05-29 19:23:50 +08:00
|
|
|
return `Sorry, we can't find CARTO user '${user}'. Please check that you have entered the correct domain.`;
|
|
|
|
}
|