Skip to content

Commit

Permalink
Merge pull request #108 from pimterry/serve-non-jwt-auth
Browse files Browse the repository at this point in the history
When serving locally, ignore non-JWT auth headers
  • Loading branch information
swyxio authored Jan 31, 2019
2 parents 473101c + 8bd211f commit 1b05e08
Showing 1 changed file with 19 additions and 13 deletions.
32 changes: 19 additions & 13 deletions lib/serve.js
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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);
};
}
Expand Down

0 comments on commit 1b05e08

Please sign in to comment.