2011-12-27 02:16:41 +08:00
|
|
|
/**
|
|
|
|
* this module allows to auth user using an pregenerated api key
|
|
|
|
*/
|
2018-02-22 18:46:34 +08:00
|
|
|
function ApikeyAuth(req, metadataBackend, username, apikey) {
|
2014-08-05 22:20:06 +08:00
|
|
|
this.req = req;
|
2018-02-22 18:46:34 +08:00
|
|
|
this.metadataBackend = metadataBackend;
|
|
|
|
this.username = username;
|
2018-02-20 02:16:33 +08:00
|
|
|
this.apikey = apikey;
|
2013-12-18 18:57:46 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = ApikeyAuth;
|
|
|
|
|
2018-02-23 00:49:02 +08:00
|
|
|
function errorUserNotFoundMessageTemplate (user) {
|
|
|
|
return `Sorry, we can't find CARTO user '${user}'. Please check that you have entered the correct domain.`;
|
|
|
|
}
|
|
|
|
|
2018-02-16 00:23:35 +08:00
|
|
|
ApikeyAuth.prototype.verifyCredentials = function (options, callback) {
|
2018-02-22 18:46:34 +08:00
|
|
|
this.metadataBackend.getApikey(this.username, this.apikey, (err, apikey) => {
|
|
|
|
if (err) {
|
|
|
|
err.http_status = 404;
|
2018-02-23 00:49:02 +08:00
|
|
|
err.message = errorUserNotFoundMessageTemplate(this.username);
|
|
|
|
|
2018-02-22 18:46:34 +08:00
|
|
|
return callback(err);
|
|
|
|
}
|
|
|
|
|
|
|
|
if (isApiKeyFound(apikey)) {
|
|
|
|
if (!apikey.grantsSql) {
|
|
|
|
const forbiddenError = new Error('forbidden');
|
|
|
|
forbiddenError.http_status = 403;
|
|
|
|
|
|
|
|
return callback(forbiddenError);
|
|
|
|
}
|
|
|
|
|
|
|
|
return callback(null, verifyRequest(this.apikey, this.apikey));
|
|
|
|
}
|
|
|
|
|
|
|
|
// Auth API Fallback
|
2018-02-27 01:13:49 +08:00
|
|
|
this.metadataBackend.getAllUserDBParams(this.username, (err, dbParams) => {
|
2018-02-22 18:46:34 +08:00
|
|
|
if (err) {
|
|
|
|
err.http_status = 404;
|
2018-02-23 00:49:02 +08:00
|
|
|
err.message = errorUserNotFoundMessageTemplate(this.username);
|
|
|
|
|
2018-02-22 18:46:34 +08:00
|
|
|
return callback(err);
|
|
|
|
}
|
|
|
|
|
|
|
|
callback(null, verifyRequest(this.apikey, dbParams.apikey));
|
|
|
|
});
|
|
|
|
});
|
2014-08-05 22:20:06 +08:00
|
|
|
};
|
|
|
|
|
2018-02-16 00:23:35 +08:00
|
|
|
ApikeyAuth.prototype.hasCredentials = function () {
|
2018-02-20 02:16:33 +08:00
|
|
|
return !!this.apikey;
|
2014-08-05 22:20:06 +08:00
|
|
|
};
|
|
|
|
|
2018-02-16 00:23:35 +08:00
|
|
|
ApikeyAuth.prototype.getCredentials = function () {
|
2018-02-20 02:16:33 +08:00
|
|
|
return this.apikey;
|
2017-11-25 00:57:54 +08:00
|
|
|
};
|
|
|
|
|
2018-02-16 00:23:35 +08:00
|
|
|
function verifyRequest(apikey, requiredApikey) {
|
2018-02-21 18:14:31 +08:00
|
|
|
return (apikey === requiredApikey && apikey !== 'default_public');
|
2014-08-05 22:20:06 +08:00
|
|
|
}
|
2018-02-22 18:46:34 +08:00
|
|
|
|
|
|
|
function isApiKeyFound(apikey) {
|
|
|
|
return apikey.type !== null &&
|
|
|
|
apikey.user !== null &&
|
|
|
|
apikey.databasePassword !== null &&
|
|
|
|
apikey.databaseRole !== null;
|
|
|
|
}
|