Experimental Long Polling in Firebase Web v9 - javascript

I am attempting to set experimentalForceLongPolling = true for Firestore settings.
The reason for this is because without this, Firestore does not work with emulators in Cypress testing.
How does one set the settings, specifically this experimentalForceLongPolling setting, in the Firebase Web v9 SDK?

You need to use initializeFirestore instead of getFirestore to update any settings as shown below:
import { initializeFirestore } from 'firebase/firestore'
const db = initializeFirestore(app, { experimentalForceLongPolling: true })

Related

Firebase authentication using google/facebook with custom nodejs server

I am trying to integrate firebase authentication with my custom nodejs server. The email/password strategy is pretty straightforward as the admin sdk supports all the operations needed. However in the case of providers, the documentation instructs us to Handle the sign-in flow manually
and get some token from either google or facebook and then send it to our nodejs server.
So when the token arrives to our nodejs server the documentation provides some code that comes from the client sdk.
This is a sample from the firebase documentation
import { getAuth, signInWithCredential, GoogleAuthProvider } from "firebase/auth";
// Build Firebase credential with the Google ID token.
const credential = GoogleAuthProvider.credential(id_token);
// Sign in with credential from the Google user.
const auth = getAuth();
signInWithCredential(auth, credential).catch((error) => {
// Handle Errors here.
const errorCode = error.code;
const errorMessage = error.message;
// The email of the user's account used.
const email = error.customData.email;
// The AuthCredential type that was used.
const credential = GoogleAuthProvider.credentialFromError(error);
// ...
});
where the id_token (probably) comes from the request body.
This flow works just fine but it is using the client sdk in a nodejs server environment because the admin sdk that is inteded for such an environment does not support this kind of operation. So, is it ok to use both SDKs, where it is needed of course, in a nodejs server?
EDIT:
What I am trying to achieve is that when the google id_token (or facebook access token) arrives in my nodejs server I need to have a way to create an account in firebase auth module with the respective provider. So with the signInWithCredential if the user does not exist then will be created and then I will issue a custom token just like I do with the email/password strategy. The only difference here is that with email/password strategy I can use the admin SDK's createUser() for the user creation.
Is this approach right?
Your approach is absolutely right :
1- You recieve google ID token from client (OAuth or etc...)
2- Sign in user to firebase using google ID:
//1 import firebase/auth
import { getAuth, signInWithCredential, GoogleAuthProvider } from "firebase/auth";
//2 configue user credentials
const credential = GoogleAuthProvider.credential(id_token);
//3 run signInWithCredential function
let userData = await signInWithCredential(auth, credential)

select_account prompt for Google Auth Provider in Firebase JS v9

In Firebase JavaScript v8, if you want to ask Google to show the account selection page every time you login, you can do:
var provider = new firebase.auth.GoogleAuthProvider();
provider.setCustomParameters({
prompt: 'select_account'
});
But with the more modular design of v9, the above syntax is not possible. How do you achieve the same result (ie., ask Google Signin to show an account selection page every time the user logs in) in this newer version of Firebase?
So, after some time I stumbled onto the same documentation that I had read before. Not sure whether they've added it recently or if my eyes were malfunctioning before, what I wrote as "not possible" in the original question is actually possible. From the documentation:
provider.setCustomParameters({
'login_hint': 'user#example.com'
});
How about writing the below code:
import { GoogleAuthProvider } from "firebase/auth";
const provider = new GoogleAuthProvider({
prompt: "select_account"
});

navigator.onLine always returning true in electron

I am developing an application using React and electron. I am planning to check the internet connection of the user. For this, navigator.online is used. However, even if I disconnect my internet connection, it always turns true and shows as if there is a connection. What I want to do is to pull data from an api if there is a connection, but to pull data from a json file. How can I check another way if the user has an internet connection?
You can try this npm package:
https://www.npmjs.com/package/is-online
Just import the isOnline function and then you can call it like this:
const isOnline = require('is-online');
...
isOnline().then(online => {
console.log(`Online? ${online}`);
...
}

Unable to use localStorage as cache location in React Native App

I am developing a React Native App with expo-cli. I am using ADFS to authenticate users in the app, and in particular, I am using MSAL.js. I've got the authentication working on web, however, I cannot get the App to run on iOS or Android. I am getting the error: "The cache location provided is not valid. Provided value: localStorage. Possible values are: localStorage, sessionStorage."
I've tried using sessionStorage instead of localStorage, but I just get the same error, except it tells me the provided value was sessionStorage.
I found a thread where someone was having a similar problem as well, here: MSAL UserAgentApplication: Local storage not working. I tried the workaround, but then I get the error: "undefined is not a constructor (evaluating 'new Msal.Storage("localStorage")')".
If I try calling Msal.Storage("localStorage"), it tells me that msal.Storage is not a function.
I've also tried explicitly passing in values to the UserAgentApplication function from my config, rather than passing in the config itself:
var myMSALObj = new Msal.UserAgentApplication(msalConfig.auth.clientId, msalConfig.auth.authority, msalConfig.auth.redirectURI, { cacheLocation: 'localStorage' });
Here's the snippet of code where I believe the problem is:
const msalConfig = {
auth: {
clientId: "<client-Id>",
authority: "<authority>",
redirectURI: "http://localhost:19006"
},
cache: {
cacheLocation: "localStorage",
storeAuthStateInCookie: true
}
};
//new Msal.Storage("localStorage");
var myMSALObj = new Msal.UserAgentApplication(msalConfig);
I would expect the call to UserAgentApplication to correctly use the localStorage as cache on both iOS and Android, but this does not seem to be the case. The app works perfectly in my browser on my laptop, though, without any cache/localStorage hiccups. Are there any workarounds/fixes for this that do not require Msal.Storage? Any help is much appreciated!
I just wrote my own library to do it. I guess MSAL.js doesn't have the right calls to work with mobile browsers.
https://yarnpkg.com/en/package/azure-ad-graph-expo
The library below does just what I want, which is log into Azure AD, retrieve a token, and then use that token to query MS graph for the appropriate user data.

Firebase, two projects same DB?

Let me explain the situation (excuse my english, I will do my best):
I have two Firebase Web projects in my Firebase console: coretechtest-ce207 and agon-plugin
coretechtest-ce207 is the main app and agon-plugin is a secondary app wich needs to connect to the auth and database of coretechtest-ce207. As far as I know I can't host two apps on the same project so thats why I made to separated projects. The main one works fine, I can do everything I want (signup, database, etc.) but I need the main and the second one both on the same auth and DB. agon-plugin (secondary one) is made based on the FriendlyChat app and connects directly to the server in wich the app is hosted.
For example:
// Initializes FriendlyChat.
function FriendlyChat() {
this.initFirebase();
}
// Sets up shortcuts to Firebase features and initiate firebase auth.
FriendlyChat.prototype.initFirebase = async function() {
// Shortcuts to Firebase SDK features.
this.auth = firebase.auth();
this.database = firebase.database();
this.storage = firebase.storage();
// Initiates Firebase auth and listen to auth state changes.
await this.auth.onAuthStateChanged(this.onAuthStateChanged.bind(this));
};
As you can see there is no need to put
apiKey: "AIzaSyAfGm_ILVdfsd--Fw7aascc8tAB73q__Bbko",
authDomain: "coretechtest-ce207.firebaseapp.com",
databaseURL: "https://coretechtest-ce207.firebaseio.com",
projectId: "coretechtest-ce207",
storageBucket: "coretechtest-ce207.appspot.com",
messagingSenderId: "994718782"
I tryied replacing it using those parameters so it would be
FriendlyChat.prototype.initFirebase = async function() {
// Shortcuts to Firebase SDK features.
this.auth = 'coretechtest-ce207.firebaseapp.com';
this.database = 'https://coretechtest-ce207.firebaseio.com';
this.storage = 'coretechtest-ce207.appspot.com';
// Initiates Firebase auth and listen to auth state changes.
await this.auth.onAuthStateChanged(this.onAuthStateChanged.bind(this));
};
But no luck there, can you tell me what I am doing wrong? I thought that replacing that would connect to my main project but it did not... =/
I hope you can understand what Im trying to say!
Thanks!
Not 100% sure about Web, but it should be similar to Android :
Going to your console panel
On top left click on the wheel next to "Project OverView"
In the pop-up click on Project Setting
In the settings page scroll down a little bit and you should see a blue "add app" (or something like that) button.
Then do everything you did on your first app to your second app
Most importantly, dont post your api key on the web !
If you're using Web and want to host 2 webapps that use the same database - you have a couple options.
Free: the only thing that associates a web app to your db is the api keys in the Firebase config used to initialize firebase in the web app. If 2 apps use those same settings then they can share the same db. If you are wanting to host both web apps with firebase for free - only 1 app can be hosted for free per project. However, you can easily create a 2nd new project and host your 2nd web app in that new project. But don't use the new web api settings from that new project inside your app. Instead use the same ones from your original project. 2 apps in 2 projects can use the same DB if they use the same API keys config. (only select firebase hosting when doing 'firebase init' from the cli for the 2nd app)
A paid option: is if you go to the Hosting page in your firebase console, and you scroll down to the bottom -you will see a card offering hosting more than 1 app in 1 project. It requires you to update to the pay-as-you-go blaze plan. Which may or may not cost you money.

Categories

Resources