Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 121 Vote(s) - 3.79 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Get Download URL from file uploaded with Cloud Functions for Firebase

#11
As of firebase 6.0.0 I was able to access the storage directly with the admin like this:

const bucket = admin.storage().bucket();

So I didn't need to add a service account. Then setting the UUID as referenced above worked for getting the firebase url.
Reply

#12
If you're working on a Firebase project, you can create signed URLs in a Cloud Function without including other libraries or downloading a credentials file. You just need to enable the IAM API and add a role to your existing service account (see below).

Initialize the admin library and get a file reference as your normally would:

import * as functions from 'firebase-functions'
import * as admin from 'firebase-admin'

admin.initializeApp(functions.config().firebase)

const myFile = admin.storage().bucket().file('path/to/my/file')

You then generate a signed URL with

myFile.getSignedUrl({action: 'read', expires: someDateObj}).then(urls => {
const signedUrl = urls[0]
})

**Make sure your Firebase service account has sufficient permissions to run this**

1. Go to the Google API console and enable the IAM API (

[To see links please register here]

)
2. Still in the API console, go to the main menu, "IAM & admin" -> "IAM"
3. Click edit for the "App Engine default service account" role
4. Click "Add another role", and add the one called "Service Account Token Creator"
5. Save and wait a minute for the changes to propagate

With a vanilla Firebase config, the first time you run the above code you'll get an error *Identity and Access Management (IAM) API has not been used in project XXXXXX before or it is disabled.*. If you follow the link in the error message and enable the IAM API, you'll get another error: *Permission iam.serviceAccounts.signBlob is required to perform this operation on service account my-service-account*. Adding the Token Creator role fixes this second permission issue.
Reply

#13
If you use the predefined access control lists value of 'publicRead', you can upload the file and access it with a very simple url structure:

// Upload to GCS
const opts: UploadOptions = {
gzip: true,
destination: dest, // 'someFolder/image.jpg'
predefinedAcl: 'publicRead',
public: true
};
return bucket.upload(imagePath, opts);

You can then construct the url like so:

const storageRoot = 'https://storage.googleapis.com/';
const bucketName = 'myapp.appspot.com/'; // CHANGE TO YOUR BUCKET NAME
const downloadUrl = storageRoot + bucketName + encodeURIComponent(dest);
Reply

#14
This is the best I came up. It is redundant, but the only reasonable solution that worked for me.

await bucket.upload(localFilePath, {destination: uploadPath, public: true});
const f = await bucket.file(uploadPath)
const meta = await f.getMetadata()
console.log(meta[0].mediaLink)
Reply

#15
You'll need to generate a signed URL using [getSignedURL][1] via the [@google-cloud/storage][2] NPM module.

Example:

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
});

You'll need to initialize `@google-cloud/storage` with [your service account credentials][3] as the application default credentials will not be sufficient.

**UPDATE**: The Cloud Storage SDK can now be accessed via the Firebase Admin SDK, which [acts as a wrapper][4] around @google-cloud/storage. The only way it will is if you either:

1. Init the SDK with a special service account, typically through a second, non-default instance.
2. Or, without a service account, by giving the default App Engine service account the "signBlob" permission.


[1]:

[To see links please register here]

[2]:

[To see links please register here]

[3]:

[To see links please register here]

[4]:

[To see links please register here]

Reply

#16
If you are getting error:

> Google Cloud Functions: require(…) is not a function

try this:


const {Storage} = require('@google-cloud/storage');
const storage = new Storage({keyFilename: 'service-account-key.json'});
const bucket = storage.bucket(object.bucket);
const file = bucket.file(filePath);
.....
Reply

#17
Without `signedURL()` using `makePublic()`

const functions = require('firebase-functions');
const admin = require('firebase-admin');

admin.initializeApp()
var bucket = admin.storage().bucket();

// --- [Above] for admin related operations, [Below] for making a public url from a GCS uploaded object

const { Storage } = require('@google-cloud/storage');
const storage = new Storage();

exports.testDlUrl = functions.storage.object().onFinalize(async (objMetadata) => {
console.log('bucket, file', objMetadata.bucket + ' ' + objMetadata.name.split('/').pop()); // assuming file is in folder
return storage.bucket(objMetadata.bucket).file(objMetadata.name).makePublic().then(function (data) {
return admin.firestore().collection('publicUrl').doc().set({ publicUrl: 'https://storage.googleapis.com/' + objMetadata.bucket + '/' + objMetadata.name }).then(writeResult => {
return console.log('publicUrl', writeResult);
});
});
});
Reply

#18
I already post my ans... in below URL Where you can get full code with solution

[To see links please register here]



const uuidv4 = require('uuid/v4');
const uuid = uuidv4();

const os = require('os')
const path = require('path')
const cors = require('cors')({ origin: true })
const Busboy = require('busboy')
const fs = require('fs')
var admin = require("firebase-admin");


var serviceAccount = {
"type": "service_account",
"project_id": "xxxxxx",
"private_key_id": "xxxxxx",
"private_key": "-----BEGIN PRIVATE KEY-----\jr5x+4AvctKLonBafg\nElTg3Cj7pAEbUfIO9I44zZ8=\n-----END PRIVATE KEY-----\n",
"client_email": "[email protected]",
"client_id": "xxxxxxxx",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://oauth2.googleapis.com/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/firebase-adminsdk-5rmdm%40xxxxx.iam.gserviceaccount.com"
}

admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
storageBucket: "xxxxx-xxxx" // use your storage bucket name
});


const app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.post('/uploadFile', (req, response) => {
response.set('Access-Control-Allow-Origin', '*');
const busboy = new Busboy({ headers: req.headers })
let uploadData = null
busboy.on('file', (fieldname, file, filename, encoding, mimetype) => {
const filepath = path.join(os.tmpdir(), filename)
uploadData = { file: filepath, type: mimetype }
console.log("-------------->>",filepath)
file.pipe(fs.createWriteStream(filepath))
})

busboy.on('finish', () => {
const bucket = admin.storage().bucket();
bucket.upload(uploadData.file, {
uploadType: 'media',
metadata: {
metadata: { firebaseStorageDownloadTokens: uuid,
contentType: uploadData.type,
},
},
})

.catch(err => {
res.status(500).json({
error: err,
})
})
})
busboy.end(req.rawBody)
});




exports.widgets = functions.https.onRequest(app);
Reply

#19
answer by

[To see links please register here]

works best

const uploadOptions: UploadOptions = {
public: true
};

const bucket = admin.storage().bucket();
[ffile] = await bucket.upload(oPath, uploadOptions);
ffile.metadata.mediaLink // this is what you need
Reply

#20
For those trying to use the token parameter to share the file and would like to use gsutil command, here is how I did it:

First you need to authenticate by running: `gcloud auth`

Then run:

`gsutil setmeta -h "x-goog-meta-firebaseStorageDownloadTokens:$FILE_TOKEN"` `gs://$FIREBASE_REPO/$FILE_NAME`

Then you can download the file with the following link:

[To see links please register here]

$FIREBASE_REPO/o/$FILE_NAME?alt=media&token=$FILE_TOKEN
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through