check user exists in user middleware

This way, we keep sending a 404 error if the user does not exist.
This commit is contained in:
Eneko Lakasta 2018-05-29 13:23:50 +02:00
parent 017dc69c02
commit fa5a99211c
4 changed files with 33 additions and 11 deletions

View File

@ -10,10 +10,6 @@ function ApikeyAuth(req, metadataBackend, username, apikey) {
module.exports = ApikeyAuth;
function errorUserNotFoundMessageTemplate (user) {
return `Sorry, we can't find CARTO user '${user}'. Please check that you have entered the correct domain.`;
}
function usernameMatches(basicAuthUsername, requestUsername) {
return !(basicAuthUsername && (basicAuthUsername !== requestUsername));
}
@ -21,8 +17,8 @@ function usernameMatches(basicAuthUsername, requestUsername) {
ApikeyAuth.prototype.verifyCredentials = function (callback) {
this.metadataBackend.getApikey(this.username, this.apikey, (err, apikey) => {
if (err) {
err.http_status = 404;
err.message = errorUserNotFoundMessageTemplate(this.username);
err.http_status = 500;
err.message = 'Unexpected error fetching from Redis';
return callback(err);
}

View File

@ -55,7 +55,7 @@ function composeJobMiddlewares (metadataBackend, userDatabaseService, jobService
return [
initializeProfilerMiddleware('job'),
userMiddleware(),
userMiddleware(metadataBackend),
rateLimitsMiddleware(userLimitsService, endpointGroup),
authorizationMiddleware(metadataBackend, forceToBeAuthenticated),
connectionParamsMiddleware(userDatabaseService),

View File

@ -36,7 +36,7 @@ QueryController.prototype.route = function (app) {
const queryMiddlewares = endpointGroup => {
return [
initializeProfilerMiddleware('query'),
userMiddleware(),
userMiddleware(this.metadataBackend),
rateLimitsMiddleware(this.userLimitsService, endpointGroup),
authorizationMiddleware(this.metadataBackend),
connectionParamsMiddleware(this.userDatabaseService),

View File

@ -1,10 +1,36 @@
const CdbRequest = require('../models/cartodb_request');
module.exports = function user () {
module.exports = function user(metadataBackend) {
const cdbRequest = new CdbRequest();
return function userMiddleware (req, res, next) {
res.locals.user = cdbRequest.userByReq(req);
next();
res.locals.user = getUserNameFromRequest(req, cdbRequest);
checkUserExists(metadataBackend, res.locals.user, function(userExists) {
if (userExists) {
return next();
} else {
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);
}
});
};
};
function getUserNameFromRequest(req, cdbRequest) {
return cdbRequest.userByReq(req);
}
function checkUserExists(metadataBackend, userName, callback) {
metadataBackend.getUserId(userName, function(err) {
callback(!err);
});
}
function errorUserNotFoundMessageTemplate(user) {
return `Sorry, we can't find CARTO user '${user}'. Please check that you have entered the correct domain.`;
}