1+
2+ const AWS = require ( 'aws-sdk' ) ;
3+ const s3 = new AWS . S3 ( ) ;
4+
5+ //https://medium.com/@yagonobre /automatically-invalidate-cloudfront-cache-for-site-hosted-on-s3-3c7818099868
6+ exports . handler = async ( event , context , callback ) => {
7+ const request = event . Records [ 0 ] . cf . request ;
8+ const uri = request . uri ;
9+
10+ if ( ! '${BUCKET_NAME}' ) {
11+ console . log ( `Bucket not defined (key is empty) => ignore` ) ;
12+ return callback ( null , request ) ;
13+ }
14+
15+ try {
16+ const filesStr = await readRestrictedFiles ( ) ;
17+ if ( ! filesStr ) {
18+ throw new Error ( `empty protect files => ignore` ) ;
19+ }
20+
21+ const rawFiles = JSON . parse ( await readRestrictedFiles ( ) ) ;
22+ if ( ! Array . isArray ( rawFiles ) ) {
23+ throw new Error ( '${BUCKET_KEY} is not any array => ignore' )
24+ }
25+ const files = rawFiles . map ( f => f . startsWith ( '/' ) ? f : '/' + f ) ;
26+ if ( ! files . includes ( uri ) ) {
27+ throw new Error ( uri + ` not protected` ) ;
28+ }
29+
30+ const headers = request . headers ;
31+
32+ const authUser = '${BASIC_USER}' ;
33+ const authPass = '${BASIC_PWD}' ;
34+
35+ const authString = 'Basic ' + new Buffer ( authUser + ':' + authPass ) . toString ( 'base64' ) ;
36+ if ( typeof headers . authorization === 'undefined' || headers . authorization [ 0 ] . value !== authString ) {
37+ const body = 'Unauthorized' ;
38+ const response = {
39+ status : '401' ,
40+ statusDescription : 'Unauthorized' ,
41+ body : body ,
42+ headers : {
43+ 'www-authenticate' : [ { key : 'WWW-Authenticate' , value :'Basic' } ]
44+ } ,
45+ } ;
46+ return callback ( null , response ) ;
47+ }
48+ }
49+ catch ( e ) {
50+ console . error ( e ) ;
51+ }
52+ return callback ( null , request ) ;
53+ } ;
54+
55+ async function readRestrictedFiles ( ) {
56+ const params = { Bucket : '${BUCKET_NAME}' , Key : '${BUCKET_KEY}' } ;
57+ const data = await s3 . getObject ( params ) . promise ( ) ;
58+ return data . Body . toString ( ) ;
59+ }
0 commit comments