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

Inject client context into functions #138

Merged
merged 1 commit into from
Apr 18, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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