diff --git a/lib/cartodb/api/get_api_key_token_from_request.js b/lib/cartodb/api/get_api_key_token_from_request.js new file mode 100644 index 00000000..6173b7c6 --- /dev/null +++ b/lib/cartodb/api/get_api_key_token_from_request.js @@ -0,0 +1,62 @@ +'use strict'; + +const basicAuth = require('basic-auth'); + +module.exports = function getApiKeyTokenFromRequest(req) { + let apiKeyToken = null; + + for (var getter of apiKeyGetters) { + (apiKeyToken = getter(req)); + if (apiKeyTokenFound(apiKeyToken)) { + break; + } + } + + return apiKeyToken; +}; + +//-------------------------------------------------------------------------------- + +const apiKeyGetters = [ + getApikeyTokenFromHeaderAuthorization, + getApikeyTokenFromRequestQueryString, + getApikeyTokenFromRequestBody, +]; + +function getApikeyTokenFromHeaderAuthorization(req) { + const credentials = basicAuth(req); + + if (credentials) { + return credentials.pass; + } else { + return null; + } +} + +function getApikeyTokenFromRequestQueryString(req) { + if (req.query.api_key) { + return req.query.api_key; + } + + if (req.query.map_key) { + return req.query.map_key; + } + + return null; +} + +function getApikeyTokenFromRequestBody(req) { + if (req.body && req.body.api_key) { + return req.body.api_key; + } + + if (req.body && req.body.map_key) { + return req.body.map_key; + } + + return null; +} + +function apiKeyTokenFound(apiKeyToken) { + return !!apiKeyToken; +}