This example demonstrates an HTTP Trigger Function serving authorized content from a static
path. Client applications pass a matching authorization token pre-defined in the function configuration - functions.config()
.
Example uses the Express framework.
See file functions/index.js for the code.
The dependencies are listed in functions/package.json.
- Clone or download this repo and open the
authorized-static
directory. - If you don't already have one, create a Firebase Project using the Firebase Console.
- If the Firebase CLI is not install, install it with
npm install -g firebase-tools
and then configure it withfirebase login
. - Configure the CLI locally by using
firebase use --add
and select your project in the list. - Install dependencies locally by running:
cd functions; npm install; cd -
- Set the
static.token
function environment variable to an authorization token you define (e.g. UUID string, etc.).
firebase functions:config:set static.token="A_TOKEN_YOU_DEFINE"
IMPORTANT: Remember to set the Authorization
header to Bearer <THE_TOKEN_YOU_DEFINED>
when making the request!
- Deploy your project using
firebase deploy --only functions
.
Example Google Apps Script to request a static file from the deployed Cloud Function.
...
function getStatic() {
var response, responseCode;
// DEVELOPER TODO: Replace "functionUrl" with the deployed Cloud Function URL from the Firebase Console
// Consider storing URL in a Google Apps Script Properties Store
var functionUrl = "https://<FIREBASE_CLOUD_FUNCTION_URL>/authorizedStatic";
// DEVELOPER TODO: Replace <TOKEN> with pre-defined token defined in the Cloud Function configuration
// Consider storing token in a Google Apps Script Properties Store
var functionToken = "<TOKEN>";
var filePath = "static";
// DEVELOPER TODO: Replace <FILENAME> with name of file to retrieve from Cloud Function e.g. "config.yml"
var fileName = "<FILENAME>";
var params = {
'method': 'GET',
'headers': {
'Authorization': 'Bearer ' + functionToken
}
};
response = UrlFetchApp.fetch(functionUrl + "/" + filePath + "/" + fileName, params);
responseCode = response.getResponseCode();
if (responseCode == 200) {
// Success fetching file from Cloud Function
return response.getContentText();
} else {
// Error returned from Cloud Function
Logger.log('Error fetching file. Response code: ' + responseCode);
return null;
}
}
...
© Laura Taylor. Licensed under an MIT license.