@@ -44,6 +44,23 @@ function promiseCallback(promise, callback) {
44
44
) ;
45
45
}
46
46
47
+ function buildClientContext ( headers ) {
48
+ // inject a client context based on auth header https://github.com/netlify/netlify-lambda/pull/57
49
+ if ( ! headers [ 'authorization' ] ) return ;
50
+
51
+ const parts = headers [ 'authorization' ] . split ( ' ' ) ;
52
+ if ( parts . length !== 2 || parts [ 0 ] !== 'Bearer' ) return ;
53
+
54
+ try {
55
+ return {
56
+ identity : { url : 'NETLIFY_LAMBDA_LOCALLY_EMULATED_IDENTITY_URL' , token : 'NETLIFY_LAMBDA_LOCALLY_EMULATED_IDENTITY_TOKEN' } ,
57
+ user : jwtDecode ( parts [ 1 ] )
58
+ } ;
59
+ } catch ( e ) {
60
+ return ; // Ignore errors - bearer token is not a JWT, probably not intended for us
61
+ }
62
+ }
63
+
47
64
function createHandler ( dir , static ) {
48
65
return function ( request , response ) {
49
66
// handle proxies without path re-writes (http-servr)
@@ -77,19 +94,8 @@ function createHandler(dir, static) {
77
94
} ;
78
95
79
96
var callback = createCallback ( response ) ;
80
-
81
- // inject a client context based on auth header https://github.com/netlify/netlify-lambda/pull/57
82
- let clientContext = { }
83
- if ( request . headers [ 'authorization' ] ) {
84
- const parts = request . headers [ 'authorization' ] . split ( ' ' )
85
- if ( parts . length === 2 && parts [ 0 ] === 'Bearer' ) {
86
- clientContext = {
87
- identity : { url : 'NETLIFY_LAMBDA_LOCALLY_EMULATED_IDENTITY_URL' , token : 'NETLIFY_LAMBDA_LOCALLY_EMULATED_IDENTITY_TOKEN' } ,
88
- user : jwtDecode ( parts [ 1 ] )
89
- }
90
- }
91
- }
92
- var promise = handler . handler ( lambdaRequest , { clientContext } , callback ) ;
97
+
98
+ var promise = handler . handler ( lambdaRequest , { clientContext : buildClientContext ( request . headers ) || { } } , callback ) ;
93
99
promiseCallback ( promise , callback ) ;
94
100
} ;
95
101
}
0 commit comments