Could not reach Cloud Firestore backend. Connection failed 1 times - android

i'm using a very simple code and fetching data from firestore
import firebase from 'firebase/app';
import 'firebase/firestore'
const firebaseApp = firebase.initializeApp({
apiKey: "...",
authDomain: "...",
....
});
const db = firebaseApp.firestore();
export default db;
but i keep getting this error
[2021-06-05T00:58:41.274Z] #firebase/firestore: Firestore (8.6.5): Could not reach Cloud Firestore backend. Connection failed 1 times.
Most recent error: FirebaseError: [code=permission-denied]:
Permission denied on resource project.
This typically indicates that your device does not have a healthy Internet connection at the moment. The client will operate in offline mode until it is able to successfully connect to the backend.
i do have a very fast internet connection
my clock is also synced with the standard time
Now, i have no clue why is this happening?
please someone help me out!!!

I was facing the same issue. The connection was working on some environments, but on my client's corporate network it wasn't.
After a loong research on the internet, I found an issue on Github talking about it.
Here's what worked for me:
const firestoreDB = initializeFirestore(firebaseApp, {
experimentalForceLongPolling: true, // this line
useFetchStreams: false, // and this line
})
Here i'm using firebase v9. For firebase v8 it's something like:
firebase().firestore().settings({
experimentalForceLongPolling: true, // this line
useFetchStreams: false, // and this line
})

i was able to resolve this issue by using my credential directly where i initializeApp my firebase config, i was previously calling them from my env file i think my app was not getting the env before

Make sure your environment is pointing to the real firestone database and not the Firestore Emulator. When I came across this same issue, that was the reason.
I'm using an Angular framework so I had to comment out those environment references in my app.module.ts file.
#NgModule({
declarations: [AppComponent, InformUserComponent],
entryComponents: [InformUserComponent],
imports: [
BrowserModule,
IonicModule.forRoot(),
AngularFireModule.initializeApp(environment.firebaseConfig),
AppRoutingModule,
ServiceWorkerModule.register('ngsw-worker.js', {
enabled: environment.production,
// Register the ServiceWorker as soon as the app is stable
// or after 30 seconds (whichever comes first).
registrationStrategy: 'registerWhenStable:30000'
}),
],
providers: [AuthService, { provide: RouteReuseStrategy, useClass: IonicRouteStrategy },
// {
// provide: USE_FIRESTORE_EMULATOR, useValue: environment.useEmulators ?
// ['localhost', 8080] : undefined
// },
// {
// provide: USE_FUNCTIONS_EMULATOR, useValue: environment.useEmulators ?
// ['localhost', 5001] : undefined
// },
],
bootstrap: [AppComponent],
})
export class AppModule { }

I had the same issue and tried to use the #atunde arisekola approach. If you can solve this problem by using direct credentials in your firebaseConfig variable, consider to check whether your .env.local or any other .env you are using is located in the root directory. In my case had firebaseConfig.ts and .env.local in the same directory, and thus the error occured. It is recommended to have.env in the root of your App.

I have faced this issue as well with angular fire.
What I have changed is to add firestore settings to the provider of app module:
According to the GitHub issues discussion, I think you can try experimentalAutoDetectLongPolling first.
And option useFetchStreams is unnecessary except for users who are using very old browser versions.
import { SETTINGS as FIRESTORE_SETTINGS } from '#angular/fire/firestore';
providers:[
{
provide: FIRESTORE_SETTINGS,
useValue: { experimentalAutoDetectLongPolling: true, merge: true },
}
]
and you can use mitmproxy to reproduce the firebase errors.

Related

How to add values to app.json for android in expo managed workflow?

I need to add those to Android files:
android:usesCleartextTraffic="true" and <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
But I'm using managed workflow and I don't know how to add those lines to app.json file.
I did this plugin which seems to work:
const { createRunOncePlugin, withAndroidManifest } = require('#expo/config-plugins');
const withAndroidManifestHavingBetterSecuritySettings = config => {
return withAndroidManifest(config, config => {
const androidManifest = config.modResults.manifest;
const mainApplication = androidManifest.application[0];
if(process.env.CHANNEL !== 'dev') {
androidManifest.$ = {
...androidManifest.$,
'xmlns:tools': 'http://schemas.android.com/tools',
};
mainApplication.$['tools:replace'] = 'android:usesCleartextTraffic';
mainApplication.$['android:usesCleartextTraffic'] = 'false';
}
return config;
});
};
module.exports = createRunOncePlugin(
withAndroidManifestHavingBetterSecuritySettings,
'withAndroidManifestHavingBetterSecuritySettings',
'1.0.0'
);
I had many issues related to merging of AndroidManifest files when "developmentClient": true in my eas.json file (related to me dev eas profile). I believe that it's related to the fact that the debug/AndroidManifest is a higher priority manifest than main/AndroidManifest (not sure though). So my solution was not to ignore the changes when building the dev profile. Hardening security settings in development builds do not seem useful anyhow.
So I struggled with this problem for a while now and the only solution I could come up with was setting the minimum sdk version of the android app from 21 to 28. This is not ideal as my application now does not support old android devices, but doing this defaults the usesClearTextTraffic flag to false.
If your app works fine while developing in expo, but after generating the APK some functions don't work, try this. In my case the APK crashed on login, but building in development with expo was working fine. The problem was that traffic is encrypted so that's why I ended up here trying to set clear text traffic. The problem in my case was with expoPushToken, in the APK it throws an exception I wasn't catching (building with expo worked fine as I said before, no exception). So, if the exception happens just catch it and set the token to empty string.
So, I had this:
import * as Notifications from "expo-notifications";
export async function getDevicePushTokenForAPP() {
const pushToken = await Notifications.getExpoPushTokenAsync();
return pushToken.data;
}
So then, I added the try and catch:
export async function getDevicePushTokenForAPP() {
try {
const pushToken = await Notifications.getExpoPushTokenAsync();
return pushToken.data;
} catch (e) {
return "";
}
}
Now if you build the APK again (expo build:android) it should work fine, in my case login worked. But please note this is for testing purposes only, I needed the APK to quickly show it to the client. (Note that you will need the bundle, not the apk, when uploading to the Playstore). This is a quick fix for you to test the APK; but with no token, push notifications won't work. The final fix is to add firebase to your project, it's mandatory now, so add firebase and with the firebase unique ID, your push notification will work in your APK.
My conclusion is that expo uses its own ID to communicate with firebase, that's why it works while developing but the APK doesn't go through expo and tries to connect to firebase directly, but crashes because there's no ID.
You should update your app.json like that:
"android": {
"usesCleartextTraffic": true,
uses-permission android:name
},

firebase apikey is missing or invalid in react native android

I'm trying to connect firebase first time with my react-native application but facing an issue which is that:
Error: Missing or invalid FirebaseOptions property 'apiKey'. I try to search to solve that problem but it doesn't solve.
import Firebase from '#react-native-firebase/app'
useEffect(()=>{
Firebase.initializeApp()
},[])
dependencies {
classpath("com.android.tools.build:gradle:4.1.0")
classpath 'com.google.gms:google-services:4.3.0'
}
Now according to my searches i do the following things to solve it
clean my android gradlew
Reinstall the node modules
Change the google-services:4.3.10 ->4.3.0
Redownload the google-serives.json file
but it doesn't work for me
I'm not sure if this helps, but I noticed you don't seem to be configuring Firebase.
This is older code from a prior project where I used Firebase (keys changed for anonymity).
Please note:
//Configure Firebase
var app = firebase.initializeApp({
apiKey: "AIzaSyBA-nJOSHcALkHfR7D7GsBqzU5qmCHY_WA",
authDomain: "project-e6136.firebaseapp.com",
databaseURL: "https://project-e6136.firebaseio.com",
projectId: "project-e6136",
storageBucket: "",
messagingSenderId: "948984656115"
});
I think you need to pass an object into the initializeApp(), with your keys.
In my case, I setup these keys at https://firebase.google.com/, when I registered an account.
Hopefully this helps, or please comment, if I misunderstood your question.

React native push notification for local notification without firebase not possible

React Native project with push notifications, I use this.
I follow this tutorial.
I only need local notifications. But if I run this project I get an error default firebaseapp is not initialized in this process.
I follow this answer and get a google service.json from firebase to make it start (notification don't show up unfortunately). But is this also possible without firebase?
requestPermissions: Platform.OS === 'ios', This line you have to add
import { Platform} from 'react-native';
PushNotification.configure({
onRegister: function (token) {
console.log("TOKEN:", token);
},
onNotification: function (notification) {
console.log("NOTIFICATION:", notification);
},
permissions: {
alert: true,
badge: true,
sound: true,
},
popInitialNotification: true,
requestPermissions: Platform.OS === 'ios',// This line you have to add //import Platform from react native
});
This package does work without firebase, after installing and setting up clear gradle cache.
On Windows:
gradlew cleanBuildCache
On Mac or UNIX:
./gradlew cleanBuildCache
Yes, it is possible to push local notification without firebase. I implemented it in one of my projects. You can take reference from this comment.
And also you don't have to call register methods from example which is available in react-native-push-notifications repo.
PS: As author did not marked any of the above answers as resolved. I hope this will work.

Firebase Invalid API key

I have an android project which I want to expand with Firebase.
Currently I've got an error logging when I want to test a crash with a log message.
Server did not receive report: Origin Error message: API key not valid. Please pass a valid API key.
What can I do to fix this?
I've copied the google-services.json file to my project from the console.
Got the same error in my Angular project. I know the question is for android but this is the question that pops up when I searched the error for angular so hopefully, it would help another person in the near future.
Make sure you're importing the right variable. In the app.module.ts file:
import { FIREBASE } from 'src/environments/firebase';
imports: [
AngularFireModule.initializeApp(FIREBASE.firebase)
],
firebase.ts (environment file) fill with your config info from firebase.
export const FIREBASE = {
production: false,
firebase: {
apiKey: "",
authDomain: "",
databaseURL: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: "",
measurementId: ""
}
};
So make sure you're importing the right variable. Took me some time to figure out. Happy coding!
Make sure you've got the API keys set correctly in your Google Developer Console for your Firebase project.
There are two different configurations for release mode and test mode. make sure that you use the API key which is related to each. In the angular there are two environment files. environment.prod.ts which is for production and environment.ts which is for testing. make sure that the api key in these files are correct.
good night, I solved this problem with
npm i firebase --save

Firebase 3 with ionic 2 google authentication

I am new to mobile app development and ionic 2. I get the google authentication working fine for a web app using angularfire2 but that doesn't work on a mobile device (yet?).
I am using ionic 2 version 2.0.0-beta.35 and firebase 3.2.1
Searching led me to the understanding that for the time being I need to use the google+ plugin for cordova, which I have installed.
I am trying this method in my ts code:
loginWithGooglePlugin()
{
return Observable.create(observer =>
{
// note for iOS the googleplus plugin requires ENABLE_BITCODE to be turned off in the Xcode
window.plugins.googleplus.login(
{
'scopes': 'profile email', // optional, space-separated list of scopes, If not included or empty, defaults to `profile` and `email`.
'webClientId': '_google_client_app_id_.apps.googleusercontent.com',
'offline': true, // optional, but requires the webClientId - if set to true the plugin will also return a serverAuthCode, which can be used to grant offline access to a non-Google server
},
function (authData)
{
console.log('got google auth data:', JSON.stringify(authData, null, 2));
let provider = firebase.auth.GoogleAuthProvider.credential(authData.idToken, authData.accessToken);
firebase.auth().signInWithCredential(provider).then((success) =>
{
console.log('success!', JSON.stringify(success, null, 2));
observer.next(success);
}, (error) =>
{
console.log('error', JSON.stringify(error, null, 2))
});
},
function (msg)
{
this.error = msg;
}
);
});
}
But the compiler keeps complaining about two things:
1. window.plugins is unknown. How can I convince ts that it's there?
There is no credential on the GoogleAuthProvider object. Searching yielded this link: firebase docs which says there was a method getCredential, which is not recognized either.
My typings seem to be fine. GoogleAuthProvider itself is recognized.
How can I fix this?
Actually, this is a bug in the typescript definitions. The Firebase team has been notified and is working on a fix. In the meantime use the following workaround:
(<any> firebase.auth.GoogleAuthProvider).credential
In my Ionic2 RC1 + Firebase3.5 + AngularFire2.beta5 project I had the same problem... Google Auth with Popup worked in Browser but not in my Android .APK
Firstly, I add 192.168.1.172 to my Firebase Console authorized domain list and <allow-navigation href="http://192.168.1.172:8100"/> to my config.xml.
After this, I found that installing Cordova InAppBrowser plugin solves my problem definitively.
I didn't need to modify my code, only plug and play, exactly like David East says in his Social login with Ionic blog.

Categories

Resources