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

Commit 758f28e

Browse files
committed
inject client context into functions
1 parent a3c355f commit 758f28e

File tree

3 files changed

+62
-12
lines changed

3 files changed

+62
-12
lines changed

package-lock.json

+35-11
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

+1
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@
3131
"http-proxy": "^1.17.0",
3232
"inquirer": "^6.2.2",
3333
"inquirer-autocomplete-prompt": "^1.0.1",
34+
"jwt-decode": "^2.2.0",
3435
"netlify": "2.4.1",
3536
"netlify-cli-logo": "^1.0.0",
3637
"node-fetch": "^2.3.0",

src/utils/serve-functions.js

+26-1
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ const queryString = require("querystring");
66
const path = require("path");
77
const getPort = require("get-port");
88
const chokidar = require("chokidar");
9+
const jwtDecode = require("jwt-decode");
910
// const chalk = require("chalk");
1011
const {
1112
NETLIFYDEVLOG,
@@ -83,6 +84,26 @@ function promiseCallback(promise, callback) {
8384
// return path.join(functionPath, `${path.basename(functionPath)}.js`);
8485
// }
8586

87+
function buildClientContext(headers) {
88+
// inject a client context based on auth header, ported over from netlify-lambda (https://github.com/netlify/netlify-lambda/pull/57)
89+
if (!headers.authorization) return;
90+
91+
const parts = headers.authorization.split(" ");
92+
if (parts.length !== 2 || parts[0] !== "Bearer") return;
93+
94+
try {
95+
return {
96+
identity: {
97+
url: "NETLIFY_LAMBDA_LOCALLY_EMULATED_IDENTITY_URL",
98+
token: "NETLIFY_LAMBDA_LOCALLY_EMULATED_IDENTITY_TOKEN"
99+
},
100+
user: jwtDecode(parts[1])
101+
};
102+
} catch (_) {
103+
// Ignore errors - bearer token is not a JWT, probably not intended for us
104+
}
105+
}
106+
86107
function createHandler(dir) {
87108
const functions = {};
88109
fs.readdirSync(dir).forEach(file => {
@@ -170,7 +191,11 @@ function createHandler(dir) {
170191
};
171192

172193
const callback = createCallback(response);
173-
const promise = handler.handler(lambdaRequest, {}, callback);
194+
const promise = handler.handler(
195+
lambdaRequest,
196+
{ clientContext: buildClientContext(request.headers) || {} },
197+
callback
198+
);
174199
promiseCallback(promise, callback);
175200
};
176201
}

0 commit comments

Comments
 (0)