From 963737d3fba2423eae3225da32cc48ef06aa81c7 Mon Sep 17 00:00:00 2001 From: Eneko Lakasta Date: Thu, 15 Feb 2018 11:36:42 +0100 Subject: [PATCH] create lib for getting api key token from request --- .../api/get_api_key_token_from_request.js | 62 +++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 lib/cartodb/api/get_api_key_token_from_request.js 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; +}