How to connect multiple Realtime Databases from the same project (Flutter) - firebase

I have created a new Realtime Database in the same project.
I followed the instructions here but got some errors.
final db = FirebaseDatabase.instance.ref(); // default database instance
// using ref()
final db2 = FirebaseDatabase.instance.ref('https://mydb2.us-central1.firebasedatabase.app');
// error Invalid Firebase Database path
// Firebase Database paths must not contain '.', '#', '$', '[', or ']'
// using refFromURL()
final db3 = FirebaseDatabase.instance.refFromURL('https://mydb2.us-central1.firebasedatabase.app');
// error Invalid argument (must equal the current FirebaseDatabase instance databaseURL)
Same goes if using
.firebaseio.com in the URL.
So what is the correct way to get DatabaseReference for secondary database in the same project?

I've figured out by using instanceFor():
final db2 = FirebaseDatabase.instanceFor(
app: Firebase.app(),
databaseURL: 'https://mydb2.us-central1.firebasedatabase.app/'
).ref();

Related

403 Error when using generated Sas token to display blobs from Azure blob storage

I've been trying to display images from Azure blob storage on my web app for a while now.
My storage account SAS token is:
?sv=2021-06-08&ss=bfqt&srt=sco&sp=rwdlacupiytfx&se=2022-12-09T08:03:09Z&st=2022-11-09T08:03:09Z&spr=https&sig=SIGNATURE_HERE
This SAS token includes all permissions and allows all resource types and services.
To generate a SAS token to view a blob, I go through the following steps:
1. Getting the blobService:
const blobService = new
BlobServiceClient(https://${storageAccountName}.blob.core.windows.net/?${storageAccountSasToken});
2. Creating a containerClient:
const containerClient = blobService.getContainerClient(containerName);
3. creating a sasOptions object:
const sasOptions = {containerName: containerName, blobName: blobName, startsOn: sasStartTime, expiresOn: sasExpiryTime, permissions: "racwdt" as unknown as BlobSASPermissions};
4. Generating SAS token with the parameters:
generateBlobSASQueryParameters(sasOptions, sharedKeyCredential).toString();
5. Sending the blobURL (with the SAS token attached) back to the user:
const blobURL = containerClient.getBlockBlobClient(blobName).url;
The problem is, when using the blobURL as src for my Image tag, I get a 403 (forbidden) error:
Server failed to authenticate the request. Make sure the value of
Authorization header is formed correctly including the signature.
the faulty blobURL in question:
https://mywebsite.blob.core.windows.net/container/profilePictures%2Fpicture.png?sv=2021-06-08&ss=bfqt&srt=sco&sp=rwdlacupiytfx&se=2022-12-09T08:03:09Z&st=2022-11-09T08:03:09Z&spr=https&sig=CITlY0uPxBCGdBeMtIxxJafJM61HQlhooR5ZnDiPHuE%3D
The Error:
AuthenticationFailed
Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature. RequestId:df81f724-f01e-000e-593e-f41f7f000000 Time:2022-11-09T13:24:08.3305270Z
Signature did not match. String to sign used was STORAGE_ACCOUNT_NAME racwdt bfqt sc 2022-11-09T12:31:47Z 2022-12-09T20:31:47Z https 2021-06-08
Additional information:
The sasToken env variable includes "?" at the start of the string
All containers are PRIVATE.
My storage account is only accessible through a specific virtual network
My website's domain is listed on "Allowed Origins" in CORS tab, as well as localhost:3000
Uploading to Blob storage works, So Its safe to assume that the problem is solely related to the generated SAS token
Any assistance would be gladly appreciated :)
I tried in my environment and got below results:
Code:
var storage = require("#azure/storage-blob")
const accountname ="storage13261";
const key = "< Account key >";
const cred = new storage.StorageSharedKeyCredential(accountname,key);
const blobServiceClient = new storage.BlobServiceClient(`https://${accountname}.blob.core.windows.net`,cred);
const containerName="test";
const client =blobServiceClient.getContainerClient(containerName)
const blobName="nature.png";
const blobClient = client.getBlobClient(blobName);
const blobSAS = storage.generateBlobSASQueryParameters({
containerName,
blobName,
permissions: storage.BlobSASPermissions.parse("racwdt"),
startsOn: new Date(),
expiresOn: new Date(new Date().valueOf() + 86400)
},
cred
).toString();
const sasUrl= blobClient.url+"?"+blobSAS;
console.log(sasUrl);
Console:
The problem is in your SAS token where storage service is uses racwdt but in you SAS has rwdlacupiytfx that may cause to display an image.
I checked the Url + SAS token in the browser it perfectly worked.
Reference:
Grant limited access to data with shared access signatures (SAS) - Azure Storage | Microsoft Learn
Updated:
You can get both SAS and SAS-URL manually with check the permission by refer the below image.

AWS Amplify DataStore not syncing with DynamoDB

My DataStore is not syncing with DynamoDB for some reason.
I've ready every issue on stackoverflow to see if I can find a resolution but no dice.
There are no errors.
Hub is showing the events firing.
Here is an example of the issue:
try {
const result = await DataStore.save(
new Employer({
name: 'Test Employer',
rate: 123.45,
}),
)
console.log('Employer saved successfully!')
console.log(result)
// const employer = await DataStore.query(Employer)
// console.log('EMPLOYER = ')
// console.log(employer)
} catch (err) {
console.log('ERROR: An error occurred during getEmployer')
console.log('Error message was ' + JSON.stringify(err))
}
DataStore nevers seems to sync with DynamoDB.
Other than that everything is fine. No issues. DataStore contains the correct data.
The only difference between my project and the code examples if that I have used Amplify Studio to build the data model and performed Amplify pull to update the project.
When I do an "amplify status" the API looks correct.
The aws-exports.js file seems to be correct.
It contains entries for Auth, API, Storage etc.
Auth is working correctly.
What am I missing?

CosmosDB migration MERN-Can't read collections

I'm exporting a database from mlabs to CosmosDb.
after failing with other methods, I finally exported via mongodump and imported into CosmosDb. I can read the collections in studio 3t.
but when connecting in Express/mongoose via the connectionString, the collections all return [].
I've added my IP to the firewall.
It's not the code, when I point back to the mlab db everything retrieves correctly.
what am I missing in CosmosDb?
issue also located here: https://learn.microsoft.com/en-us/answers/questions/153583/cosmosdb-migration-mern-can39t-read-collections.html?childToView=154602#answer-154602
in azure, the generated connection strings don't quite match what the exercise sent by Kaylan sent. and I also wasn't setting some of the options. without the options I get a message "Password contains an illegal unescaped character"
the Primary Connection string and Secondary Connection String add the following:
&retrywrites=false
&maxIdleTimeMS=120000
&appName=#<appName>#
once I removed that from the connection string AND used the options, things worked.
my final connection example:
//pulled from config for clarity
const config = {
'database': process.env.MONGODB_URI || 'mongodb://<user>:<password>#<db>.mongo.cosmos.azure.com:10255/<dbname>?ssl=true&replicaSet=globaldb'
}
mongoose.connect(config.database, //with user and pass inside
{
useNewUrlParser: true,
useUnifiedTopology: true,
retryWrites: false,
useFindAndModify: false,
useCreateIndex: true
})
//.then(() => console.log('Connection to CosmosDB successful'))
.catch((err) => console.error('CosmosDB error:', err))

Obtaining the URL to an Already Stored File in Firebase Storage through Flutter

I'm currently trying to access the URL to a file from Firebase Storage without logging into the Firebase Console and grabbing the URL by hand. I'm developing an app that will be able to obtain that URL and store it as a string.
I've been hitting a lot of walls when doing this through Flutter and I've tried searching SO for a means of obtaining the URL programmatically.
So far, I've tried one method that looks like it works, but it isn't actually performing the task that I had intended for it to do.
void getDownloadUrl(String audioName) {
FirebaseStorage firebaseStorage = FirebaseStorage.instance;
StorageReference songRef = firebaseStorage.ref().child('$audioName');
songRef.getMetadata().then(
(_) => print('successfully accessed firebase storage child'),
onError: (_) =>
print("Wasn't able to access metadata from " + songRef.path));
String audioString;
songRef
.getDownloadURL()
.then((_) => audioString = songRef.getDownloadURL().toString());
String audioPath;
if (firebaseStorage != null) {
audioPath = firebaseStorage.ref().child('$audioName').path;
} else {
print('songNameString is null. Check $audioPath');
}
}
This is one method I've tried and it is still unsuccessful.
Can someone please explain the best practice for accessing Firebase Storage, search through the folder, get a hold of a file and access the required URL that can be stored for later use as that is the main goal I have for this section?
I have also opened permissions for read/write access to Firebase Storage.
Just to be clear - I'm not uploading a file through the app. So I don't think I'll be able to call the event that returns a URL upon upload.
Try This :
printPath() async {
StorageReference ref =
FirebaseStorage.instance.ref().child('example/audio abc.mp3');
String url = (await ref.getDownloadURL()).toString();
print('Urlllllllllllllll $url');
}
Above code working fine .See below Screeenshot for refrence ;
Click Here to see the Image

React-native Firebase storage upload using putString call

I'm setting up this thread in order to clarify, whether firebase storage putString method does or does not work in React-native.
From what I've searched there is currently no way to upload File or Blob types to Firebase Storage using put method.
React Native does not support the File and Blob types, so Firebase Storage uploads will not work in this environment. File downloads do work however.
SOURCE: The Firebase Blog
Thus this call
firebase.storage().ref()
.child(userID)
.put(new File(['this is a small amount of data'], 'sample-text.txt', { type: "text/plain" }), { type: "text/plain" })
.then(p => {console.log(p)})
.catch(p => {console.log(p)})
does not work and ends up with response
code : "storage/unknown" message : "Firebase Storage: An unknown error
occurred, please check the error payload for server response." name :
"FirebaseError" serverResponse : "Multipart body does not contain 2 or
3 parts."
Nevertheless there is another option to upload data to Firebase Storage, using Firebase storage putString method. Which works with plain string. But even if I use this method to upload. I'm getting the same server reponse as before.
firebase.storage()
.ref()
.child(userID)
.putString('string')
.then(p => {console.log(p)})
.catch(p => {console.log(p)});
Bu from what I've learned from this answer. The putString way should work.
What am I doing wrong? The code works fine for me in React. Whenever I paste to React-native. It stops working.
I've just tried react-native-fetch-blob as Ven commented before, and I was able to make it work, try using this snippet from the index file in the example:
1) Before class declaration:
import RNFetchBlob from 'react-native-fetch-blob';
const Blob = RNFetchBlob.polyfill.Blob;
window.XMLHttpRequest = RNFetchBlob.polyfill.XMLHttpRequest;
window.Blob = Blob;
2) Inside the storing method:
let filePath = 'YOUR/FILE/PATH';
let fileName = 'file_name.jpg';
let rnfbURI = RNFetchBlob.wrap(filePath);
// create Blob from file path
Blob
.build(rnfbURI, { type : 'image/png;'})
.then((blob) => {
// upload image using Firebase SDK
firebase.storage()
.ref('images')
.child(fileName)
.put(blob, { contentType : 'image/jpg' })
.then((snapshot) => {
console.log('Uploaded', snapshot.totalBytes, 'bytes.');
console.log(snapshot.metadata);
var url = snapshot.metadata.downloadURLs[0];
console.log('File available at', url);
}).catch(function(error) {
console.error('Upload failed:', error);
});

Resources