Windshaft-cartodb/lib/api/middlewares/credentials.js

88 lines
1.9 KiB
JavaScript
Raw Normal View History

'use strict';
2018-03-12 18:52:38 +08:00
const basicAuth = require('basic-auth');
2018-03-12 18:52:38 +08:00
module.exports = function credentials () {
2019-10-22 01:07:24 +08:00
return function credentialsMiddleware (req, res, next) {
const apikeyCredentials = getApikeyCredentialsFromRequest(req);
2018-03-12 18:52:38 +08:00
res.locals.api_key = apikeyCredentials.token;
2018-03-12 18:52:38 +08:00
res.locals.basicAuthUsername = apikeyCredentials.username;
2019-10-22 01:07:24 +08:00
res.set('vary', 'Authorization'); // Honor Authorization header when caching.
2018-03-12 18:52:38 +08:00
return next();
};
};
2019-10-22 01:07:24 +08:00
function getApikeyCredentialsFromRequest (req) {
let apikeyCredentials = {
token: null,
2019-10-22 01:07:24 +08:00
username: null
};
2019-10-22 01:07:24 +08:00
for (const getter of apikeyGetters) {
apikeyCredentials = getter(req);
if (apikeyTokenFound(apikeyCredentials)) {
break;
}
}
return apikeyCredentials;
}
const apikeyGetters = [
getApikeyTokenFromHeaderAuthorization,
getApikeyTokenFromRequestQueryString,
2019-10-22 01:07:24 +08:00
getApikeyTokenFromRequestBody
];
2019-10-22 01:07:24 +08:00
function getApikeyTokenFromHeaderAuthorization (req) {
const credentials = basicAuth(req);
if (credentials) {
return {
username: credentials.username,
token: credentials.pass
};
} else {
return {
username: null,
2019-10-22 01:07:24 +08:00
token: null
};
}
}
2019-10-22 01:07:24 +08:00
function getApikeyTokenFromRequestQueryString (req) {
let token = null;
if (req.query && req.query.api_key) {
token = req.query.api_key;
} else if (req.query && req.query.map_key) {
token = req.query.map_key;
}
return {
username: null,
2019-10-22 01:07:24 +08:00
token: token
};
}
2019-10-22 01:07:24 +08:00
function getApikeyTokenFromRequestBody (req) {
let token = null;
if (req.body && req.body.api_key) {
token = req.body.api_key;
} else if (req.body && req.body.map_key) {
token = req.body.map_key;
}
return {
username: null,
2019-10-22 01:07:24 +08:00
token: token
};
}
2019-10-22 01:07:24 +08:00
function apikeyTokenFound (apikey) {
return !!apikey && !!apikey.token;
}