CartoDB-SQL-API/lib/auth/apikey.js

75 lines
2.1 KiB
JavaScript
Raw Normal View History

2018-10-24 21:42:33 +08:00
'use strict';
2011-12-27 02:16:41 +08:00
/**
* this module allows to auth user using an pregenerated api key
*/
2019-12-24 01:19:08 +08:00
function ApikeyAuth (req, metadataBackend, username, apikeyToken) {
this.req = req;
this.metadataBackend = metadataBackend;
this.username = username;
2018-06-05 19:13:09 +08:00
this.apikeyToken = apikeyToken;
}
module.exports = ApikeyAuth;
2019-12-24 01:19:08 +08:00
function usernameMatches (basicAuthUsername, requestUsername) {
2018-05-17 23:13:59 +08:00
return !(basicAuthUsername && (basicAuthUsername !== requestUsername));
}
2018-02-27 02:02:05 +08:00
ApikeyAuth.prototype.verifyCredentials = function (callback) {
2018-06-05 19:13:09 +08:00
this.metadataBackend.getApikey(this.username, this.apikeyToken, (err, apikey) => {
if (err) {
err.http_status = 500;
2018-06-06 21:23:53 +08:00
err.message = 'Unexpected error';
2018-02-23 00:49:02 +08:00
return callback(err);
}
2018-05-18 17:35:54 +08:00
if (isApiKeyFound(apikey)) {
2018-05-17 23:13:59 +08:00
if (!usernameMatches(apikey.user, this.username)) {
2018-05-18 17:35:54 +08:00
const usernameError = new Error('Forbidden');
usernameError.type = 'auth';
usernameError.subtype = 'api-key-username-mismatch';
usernameError.http_status = 403;
2018-05-17 23:13:59 +08:00
2018-05-18 17:35:54 +08:00
return callback(usernameError);
2018-05-17 23:13:59 +08:00
}
2018-10-24 21:42:33 +08:00
if (!apikey.grantsSql) {
const forbiddenError = new Error('forbidden');
forbiddenError.http_status = 403;
return callback(forbiddenError);
}
return callback(null, getAuthorizationLevel(apikey));
2019-12-24 01:19:08 +08:00
} else {
2018-05-18 17:35:54 +08:00
const apiKeyNotFoundError = new Error('Unauthorized');
apiKeyNotFoundError.type = 'auth';
apiKeyNotFoundError.subtype = 'api-key-not-found';
apiKeyNotFoundError.http_status = 401;
2018-10-24 21:42:33 +08:00
return callback(apiKeyNotFoundError);
}
});
};
ApikeyAuth.prototype.hasCredentials = function () {
2018-06-05 19:13:09 +08:00
return !!this.apikeyToken;
};
ApikeyAuth.prototype.getCredentials = function () {
2018-06-05 19:13:09 +08:00
return this.apikeyToken;
};
2019-12-24 01:19:08 +08:00
function getAuthorizationLevel (apikey) {
return apikey.type;
}
2019-12-24 01:19:08 +08:00
function isApiKeyFound (apikey) {
return apikey.type !== null &&
apikey.user !== null &&
apikey.databasePassword !== null &&
apikey.databaseRole !== null;
}