Skip to content
This repository has been archived by the owner on Sep 12, 2019. It is now read-only.

Commit

Permalink
Merge pull request #138 from irreal/master
Browse files Browse the repository at this point in the history
Inject client context into functions
  • Loading branch information
swyxio authored Apr 18, 2019
2 parents a3c355f + 758f28e commit bdd8489
Show file tree
Hide file tree
Showing 3 changed files with 62 additions and 12 deletions.
46 changes: 35 additions & 11 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
"http-proxy": "^1.17.0",
"inquirer": "^6.2.2",
"inquirer-autocomplete-prompt": "^1.0.1",
"jwt-decode": "^2.2.0",
"netlify": "2.4.1",
"netlify-cli-logo": "^1.0.0",
"node-fetch": "^2.3.0",
Expand Down
27 changes: 26 additions & 1 deletion src/utils/serve-functions.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ const queryString = require("querystring");
const path = require("path");
const getPort = require("get-port");
const chokidar = require("chokidar");
const jwtDecode = require("jwt-decode");
// const chalk = require("chalk");
const {
NETLIFYDEVLOG,
Expand Down Expand Up @@ -83,6 +84,26 @@ function promiseCallback(promise, callback) {
// return path.join(functionPath, `${path.basename(functionPath)}.js`);
// }

function buildClientContext(headers) {
// inject a client context based on auth header, ported over from netlify-lambda (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 (_) {
// Ignore errors - bearer token is not a JWT, probably not intended for us
}
}

function createHandler(dir) {
const functions = {};
fs.readdirSync(dir).forEach(file => {
Expand Down Expand Up @@ -170,7 +191,11 @@ function createHandler(dir) {
};

const callback = createCallback(response);
const promise = handler.handler(lambdaRequest, {}, callback);
const promise = handler.handler(
lambdaRequest,
{ clientContext: buildClientContext(request.headers) || {} },
callback
);
promiseCallback(promise, callback);
};
}
Expand Down

0 comments on commit bdd8489

Please sign in to comment.