Firebase Auth JS signInWithCustomToken hangs - firebase

I'm using Ionic+Capacitor to build an app, and in the iOS WebView, this line hangs:
const userCredential = await signInWithCustomToken(auth, token.data.result);
I see on my Firebase console that the user is created when I make the call, so I know it has the intended effect, and I've wrapped it in a try/catch in case it's throwing, but the error bloc never gets called & the function hangs indefinitely. Has anyone else run into issues with this function hanging? Is there a known workaround? Thanks!

Related

Permission errors unit-testing Google Cloud Functions calling firestore db

I'm following the guide at https://firebase.google.com/docs/functions/unit-testing, but I always get " FirebaseError: Missing or insufficient permissions" when I run my test. I have the correct service-account.json file and I'm setting up firebase-functions-test with it (that part goes without error).
I've tried it with the emulator running (setting the FIRESTORE_EMULATOR_HOST var), and without it (which I assume uses live data) but I always get this error, as soon as my code under test does a db request such as:
data = await db().collection('/machines').get()
So my function under test is getting called, but it just can't do anything.
I also tried calling firebase.initializeApp() the same way I do in my front-end app, but that doesn't help, although without it I get the error telling me to call Firebase App.initializeApp().
firebase use is set to my current project.
I also tried running my test as firebase emulators:exec jest, no difference.
Any ideas?

Firebase Functions: Could not load default credentials

I have a Firebase Function that subscribes to a Cloud PubSub topic. App is initialized very simply like this:
import * as admin from 'firebase-admin';
admin.initializeApp();
I'm getting this error:
"Error: Could not load the default credentials. Browse to https://cloud.google.com/docs/authentication/getting-started for more information.
at GoogleAuth.getApplicationDefaultAsync (/srv/functions/node_modules/google-auth-library/build/src/auth/googleauth.js:161:19)
at process._tickCallback (internal/process/next_tick.js:68:7)"
Here's the weird thing. It typically works. In other words, if I trigger it a second time it works. And a third time. Most often it seems to fail the first time it runs after a new firebase deploy and possibly on a "cold start."
Not sure what I'm doing wrong and why it would fail only on the first run.
SOLVED! This answer helped:
Error: Could not load the default credentials (Firebase function to firestore)
From within a Firebase Function for an API call, I was publishing to a Cloud PubSub topic like this:
pubsub.topic(topicName).publish(dataBuffer, customAttributes)
I was not awaiting the response and was immediately sending the 2XX HTTP response back to the client. The execution seemed to continue fine, but obviously it did not behave as intended.
Sometimes the API response call itself would fail (and never publish the message), but sometimes not. In other cases, the publish would succeed but the Firebase Function subscribing to the topic would fail!
In all cases, this seemed to resolve itself after running the script a second time. For this reason, I still believe it had something to do with a cold start.
But since I changed it to await like this:
await pubsub.topic(topicName).publish(dataBuffer, customAttributes)
I have not seen this problem happen again.

Using Offline Persistence in Firestore in a Flutter App

I'm developing a app that uses Firebase's Firestore to send data to the web. One of the functions of the app is being able to save data in the device while being offline and send it to Firestore when internet connection is restored.
I activated offline persistence but it dosen't work.
DEBUG CONSOLE:
W/OkHttpClientTransport(28536): Failed closing connection
W/OkHttpClientTransport(28536): javax.net.ssl.SSLException: Write error: ssl=0x7f7acfc408: I/O error during system call, Broken pipe
W/OkHttpClientTransport(28536): at com.google.android.gms.org.conscrypt.NativeCrypto.SSL_write(Native Method)
W/OkHttpClientTransport(28536): at com.google.android.gms.org.conscrypt.NativeSsl.write(:com.google.android.gms#14798020#14.7.98 (040406-222931072):4)
How can I activate offline persistence and sync with Firestore when internet is restored?
MY CODE:
Future<Null> sendFirebaseData(var selectedModel) async {
Firestore.instance.enablePersistence(true);
var certID = await getIDCertificado();
var dateTime = new DateTime.now();
var nowHour = new DateFormat('kk:mm:ss').format(dateTime);
Map<String, dynamic> dataHeader = {
'ID': certID,
};
Map<String, dynamic> finalDataMap = {}..addAll(dataGeneral)
..addAll(dataInstrumento)..addAll(dataPadrao)
..addAll(dataAdicional)..addAll(dataHeader);
await Firestore.instance.collection('certificados').document((certID.toString()))
.setData(finalDataMap);}
when you use offline persistence in Firestore, don't use Transactions or await for response.
so, change this :
await Firestore.instance.collection('certificados').document((certID.toString()))
.setData(finalDataMap);
to this:
Firestore.instance.collection('certificados').document((certID.toString()))
.setData(finalDataMap);
When you restore your internet connection your data will be sync automatically, even if you are in background.
Doesn't work when your app is closed.
Context Of Promises & Callbacks when Offline
Why the above code change to remove "await" works.
Reference: Firebase Video - How Do I Enable Offline Support 11:13
Your callback won't be called and your promise won't complete until the document write has been successful on the server. This is why if your UI waits until the write completes to do something, it appears to freeze in "offline mode" even if the write was actually made to the local cache.
It is OK to not use async / await, .then() or callbacks. Firestore will always "act" as if the data change was applied immediately, so you don't need to wait to be working with fresh data.
You only need to use callbacks and promises when you need to be sure that a server write has happened, and you want to block other things from happening until you get that confirmation.
I think the currrent answer is outdated. According to the firebase documentation, offline persistentence is enabled by default for Android and iOS. For the web, it is not.
In flutter, the firestore implementation is based on the underlying OS. So you're safe on mobile apps, but not with flutter for web.
It is enabled by default but still only when you are not using await or transactions, further you can use timeout to stop listening to network connection by firestore after a specific time.
ref.setData(newNote.toMap()).timeout(Duration(seconds: 2),onTimeout:() {
//cancel this call here
print("do something now");
});

Firebase React Native Functions seemingly not executing

I have been using one machine to develop and recently had to switch over to another. I have been going crazy all day because I thought the code was broken (worked on one machine) but then I realized, for some reason anything firebase related will not run. Such as the example code, just seemingly will not execute at all.
Just fyi I am using react native. I read that firebase just recently started supporting it, so I figured there might be some problems. I did the npm install and all that..
This block just simply auth the user. I have used it before and know it works. But for some reason just simply will not execute.
console.log("Start")
firebaseObject.auth().signInWithEmailAndPassword(this.state.email, this.state.password).then(function() {
console.log("Sign In, Go to login")
}.bind(this), function(error) {
// An error happened.
var errorCode = error.code;
var errorMessage = error.message;
console.log("ERROR WITH SIGNIN")
console.log( errorMessage )
});
console.log("end")
if I run this, it will print "Start" and "end" but not run that signInWithEmailandPassword
I've been struggling with the same problem for a week...
I have tried running Firebase in redux-thunks as well as in Redux Sagas, besides trying it directly in a component.
Have you had any luck? It seems Firebase itself is working in on itself (I can make refs), but all async calls just hang there forever, no resolve, no errors either.

authWithCustomToken not firing callback

When a user registers on my system, I create the user internally, and then allow the user to register with Firebase using the firebase client lib. This generates a session token for the user. Later, when a user starts the app again, the app automatically logs the user in like this:
ref.authWithCustomToken(sessionToken, function(error, authData) {...
debugger
I have verified that the sessionToken is available when the function is executed, but debugger is never reached, and no error is ever emitted.
Any help is appreciated!
I know it's a bit late, but I experienced a similar problem and it had me scratching my head for a while, so just in case it helps somebody else, here's what I found.
If I run authWithCustomToken with a token generated with one uid (uid1) and then run it again on the same ref with a different uid (uid2), the callback doesn't get fired the second time around.
In my case, I had declared the same ref in different modules that were used in the same node process and was trying to authenticate them with different uids. Although I had declared the ref twice, Firebase still saw it as the same ref because it was in the same process and referred to the same Firebase location. By declaring and authorising the ref in a parent module, I was then able to use onAuth in the child modules and the onAuth callbacks all fired as expected.
I had a similar problem with iOS, authWithCustomToken callback was never called right after install.
All consecutive launches worked fine.
My findings might be related so I thought I share them.
Problem was I called
func applicationWillResignActive(application: UIApplication) {
Firebase.goOffline()
}
func applicationWillEnterForeground(application: UIApplication) {
Firebase.goOnline()
}
in AppDelegate. Turns out if you call Firebase.goOnline() without logging in first it messes up the callback. Once I removed those two lines everything worked fine.

Resources