Google Firebase - Polymerfire, getting a callback on the initial application initialization - javascript

Is there anyway to do something like this with firebase.
var loaded = false;
var app = firebase.initializeApp(config);
app.then(function(user) {
// initialization complete
loaded = true;
if(user){
// user logged in
}
else
{
// user not logged in
}
});
The above solution, if possible, would provide me with the knowledge that a user has or has not been logged in, as well as the information the application is attempting to get a user.
I can then only show the page to the user once I know that the page is not going to change in the next second.

Related

Getting Uncaught TypeError in Firebase Auth get current user email

I am trying to get the email of the currently signed in user in my Firebase app, but it keeps giving me an error.
This is my code for getting the current user email:
user_email = firebase.auth().currentUser.email
The error that I get is:
Error Image
It looks like firebase.auth().currentUser is null at the time when your firebase.auth().currentUser.email runs. This is quite common, as Firebase refreshes the user's authentication state when the page loads, and this requires it to make an asynchronous call to the server.
For this reason, you should not assume there is a user signed in. You should either put a check around your current code:
if (firebase.auth().currentUser) {
user_email = firebase.auth().currentUser.email
}
Or (and often better) you should use a so-called auth state listener, to have your code automatically respond to changes in the user's authentication state. From the Firebase documentation on getting the currently signed-in user, that'd be:
firebase.auth().onAuthStateChanged((user) => {
if (user) {
// User is signed in, see docs for a list of available properties
// https://firebase.google.com/docs/reference/js/firebase.User
var uid = user.uid;
user_email = firebase.auth().currentUser.email;
// TODO: execute code that needs `user_email`
} else {
// User is signed out
// ...
}
});

Firebase initialize app lose Current User

I have a web application using html-js-css and a flask server.
My web app is a multi-pages app which apparently means that I have to Initialize firebase for each page in which i want to use it -.-
The problem is that every time I initialize firebase app, I lose the current user so while in my main page, after log-in, if I write:
const USER = firebase.auth().currentUser;
console.log(USER.uid);
I get my user ID, as soon as I move to another page and repeat the above code, I get the error:
TypeError: USER is null
Is there a way to either:
avoid Initializing the firebase-app at avery page
keep the CurrentUser (even storing it securely somewhere)
Thank you
Workaround:
I got this workaround working before Frank answer which is probably the best way to proceed. Instead I just stored the user id in an encrypted variable accessible to all pages.
Since the main.html page is always loaded, I store/removed the variable in a onAuthStateChanged listener there so as soon as the user is logged out, that variable is removed:
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
cached_uid = JSON.stringify(user.uid);
cached_uid = btoa(cached_uid);
localStorage.setItem('_uid',cached_uid);
} else {
localStorage.removeItem('_uid');
}
});
then on the other pages:
function loadUID(){
var uid = localStorage.getItem('_uid');
if (!uid) return false;
uid = atob(uid);
uid = JSON.parse(uid);
return uid
}
I followed this to find this solution:
How to send variables from one file to another in Javascript?
You will need to initialize the Firebase app on each page, but that is supposed to be a fairly cheap operation.
To pick up the user on the new page, Firebase runs a check against the server to ensure the user token is still valid. Since this code calls a server, its result likely isn't available yet when your firebase.auth().currentUser runs.
To solve this, run the code that requires a user in a so-called auth state change listener:
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
} else {
// No user is signed in.
}
});
Also see the Firebase documentation on getting the currently signed in user.

Keep user after redirect with firebase

Im currently working on a side project with firebase on web and it uses user auth. I have the user logging in and then creating a game room which redirects to a separate page for the game "room". After the page redirects though i cannot pull any of the users data and the only way that im doing it is by re initializing firebase and using
auth.onAuthStateChanged(function(user) {
if (user && user != null) {
uid = user.uid;
email = user.email;
currUser = user;
} else {
//user isnt logged in
window.location.href = 'index.html';
}
There seems to probably be an easier way to do this but i cant seem to get it working and this way also messes up sections of my other code.
Attaching an onAuthStateChanged callback is the idiomatic way to get the user.
You can also get the user with firebase.auth().currentUser. But if a token refresh is required, you may in that case mis-detect that there is no user. That why an onAuthStateChanged callback is recommended.
See the Firebase documentation on getting the current user.

Firebase: Store anonymous authentication in cookies

I am developing multi page application, that uses firebase as a back-end.
On every page after firebase initialization I have the following code:
firebase.auth().signInAnonymously().catch(...);
firebase.auth().onAuthStateChanged(function(user)
{
if (user) {
// ...
} else {
// User is signed out.
// ...
}
// ...
});
which sign in every visitor anonymously.
The problem is, when user navigates to another page of my application or opens it in a new tab, or just refreshes the current page - new anonymous user is generated.
I can use client side cookies to store anonymous user id, but how can I later (after page refresh) use that stored anonymous user id, to sign in user with that id?
It was my mistake,
firebase store anonymous user authorization in local storage by default.
My code sample should be rewritten this way to work properly:
firebase.auth().onAuthStateChanged(function(user)
{
if (user) {
// User is signed in
// ...
} else {
// User is signed out.
firebase.auth().signInAnonymously().catch(/*...*/);
}
// ...
});

How to manage google sign-in session (Google Sign-In JavaScript client)

im trying to implement google sign-in using their new API : https://developers.google.com/identity/sign-in/web/
Sign-in and Sign-out work fine.
My problem is that i dont know how to manage a session on other pages without a server side.
So i tried this code - https://developers.google.com/identity/sign-in/web/session-state
And it doesnt work well for me.
I dont want to have the google sign in button in every page. If i remove the "auth2.attachClickHandler.." part the whole code doesnt work.
All i want is to indicate in other pages (not in the page with the google button) if a user is still connected to or not.
Can you help me?
EDIT:
I tried the following code suggested in the answers but i get an error that says: " Uncaught TypeError: Cannot read property 'init' of undefined"
Code:
var auth2 = gapi.auth2.init({
client_id : 'ID.apps.googleusercontent.com'
});
auth2.then(function() {
var isSignedIn = auth2.isSignedIn.get();
var currentUser = auth2.currentUser.get();
if (isSignedIn) {
console.log("signed in");
// User is signed in.
// Pass currentUser to onSignIn callback.
} else {
console.log("NOT signed in");
// User is not signed in.
// call auth2.attachClickHandler
// or even better call gapi.signin2.render
}
});
You can load gapi.auth2 on all pages and call:
var auth2 = gapi.auth2.init(...);
auth2.then(function() {
var isSignedIn = auth2.isSignedIn.get();
var currentUser = auth2.currentUser.get();
if (isSignedIn) {
// User is signed in.
// Pass currentUser to onSignIn callback.
} else {
// User is not signed in.
// call auth2.attachClickHandler
// or even better call gapi.signin2.render
}
});
In this solution sign in button is displayed only when user is not signed in.

Categories