Skip to content

Instantly share code, notes, and snippets.

@sketchthat
Created September 1, 2017 22:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sketchthat/860b0a6b8e27852bffe1a5f5ccaa5548 to your computer and use it in GitHub Desktop.
Save sketchthat/860b0a6b8e27852bffe1a5f5ccaa5548 to your computer and use it in GitHub Desktop.
const functions = require('firebase-functions');
const gcs = require('@google-cloud/storage')();
exports.listener = functions.database.ref('/test/storage').onWrite(() => {
const bucket = gcs.bucket(functions.config().firebase.storageBucket);
const filePath = __dirname + '/image.png';
return bucket.upload(filePath, { destination: 'storage-folder/sample/test-image.png' })
.then(files => {
const file = files[0];
return file.getSignedUrl({ action: 'read', expires: '01-01-2020' });
})
.then(url => {
console.log('Signed URL: ', url);
})
.catch(err => {
console.error('Error: ', err);
});
});
/**
Error: { SigningError: Could not get credentials without a JSON, pem, or p12 keyfile.
at /user_code/node_modules/@google-cloud/storage/src/file.js:1479:16
at getAuthClient (/user_code/node_modules/@google-cloud/storage/node_modules/google-auto-auth/index.js:132:9)
at runCallback (timers.js:672:20)
at tryOnImmediate (timers.js:645:5)
at processImmediate [as _immediateCallback] (timers.js:617:5)
message: 'Could not get credentials without a JSON, pem, or p12 keyfile.' }
**/
@sketchthat
Copy link
Author

Solution on stackoverflow suggests including the key - which is annoying when moving between environments. Can't pickup and move between a staging / production environment.

Making matters worse, you can't store the PEM file in the firebase config options because there is a bug in the handling of /n.
firebase/firebase-tools#371

const gcs = require('@google-cloud/storage')({keyFilename: 'service-account.json'});
// ...
const bucket = gcs.bucket(bucket);
const file = bucket.file(fileName);
return file.getSignedUrl({
  action: 'read',
  expires: '03-09-2491'
}).then(signedUrls => {
  // signedUrls[0] contains the file's public URL
});

@sketchthat
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment