diff --git a/lib/serve.js b/lib/serve.js index 09c807e4..4764a871 100644 --- a/lib/serve.js +++ b/lib/serve.js @@ -44,6 +44,23 @@ function promiseCallback(promise, callback) { ); } +function buildClientContext(headers) { + // inject a client context based on auth header https://github.com/netlify/netlify-lambda/pull/57 + if (!headers['authorization']) return; + + const parts = headers['authorization'].split(' '); + if (parts.length !== 2 || parts[0] !== 'Bearer') return; + + try { + return { + identity: { url: 'NETLIFY_LAMBDA_LOCALLY_EMULATED_IDENTITY_URL', token: 'NETLIFY_LAMBDA_LOCALLY_EMULATED_IDENTITY_TOKEN' }, + user: jwtDecode(parts[1]) + }; + } catch (e) { + return; // Ignore errors - bearer token is not a JWT, probably not intended for us + } +} + function createHandler(dir, static) { return function(request, response) { // handle proxies without path re-writes (http-servr) @@ -77,19 +94,8 @@ function createHandler(dir, static) { }; var callback = createCallback(response); - - // inject a client context based on auth header https://github.com/netlify/netlify-lambda/pull/57 - let clientContext = {} - if (request.headers['authorization']) { - const parts = request.headers['authorization'].split(' ') - if (parts.length === 2 && parts[0] === 'Bearer') { - clientContext = { - identity: { url: 'NETLIFY_LAMBDA_LOCALLY_EMULATED_IDENTITY_URL', token: 'NETLIFY_LAMBDA_LOCALLY_EMULATED_IDENTITY_TOKEN' }, - user: jwtDecode(parts[1]) - } - } - } - var promise = handler.handler(lambdaRequest, { clientContext }, callback); + + var promise = handler.handler(lambdaRequest, { clientContext: buildClientContext(request.headers) || {} }, callback); promiseCallback(promise, callback); }; }