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

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.

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.

Firebase google auth does not sign out completely

Using the very clear simple examples provided by Google (Firebase Google Auth)I have been unable to log out from google.
Everytime sign I call this method using a button, it allows me to log in and navigates me to the local host.
function logGoogle() {
firebase.auth().signInWithPopup(provider).then(function(result) {
// This gives you a Google Access Token. You can use it to access the Google API.
var token = result.credential.accessToken;
// The signed-in user info.
var user = result.user;
location.href = 'http://localhost:8080';
// ...
}).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// The email of the user's account used.
var email = error.email;
// The firebase.auth.AuthCredential type that was used.
var credential = error.credential;
// ...
console.log(errorCode);
console.log(errorMessage);
console.log(email);
console.log(credential);
});
}
however when i go back to the main menu which consists a log out button. It logs the session out, doesn't delete the session. When i log back in, i do not need to enter google creds. Bear in mind i am logged in to google chrome using an gmail account.
function logOutGoogle() {
firebase.auth().signOut().then(function () {
console.log("you logged off");
location.href = 'http://localhost/GoogleVue3/';
}).catch(function (error) {
alert(error);
});
}
I tried in incognito mode. entered google creds, went to the app, and decided to log out. Click on to sign in google, it automatically takes me to the app.
any advices?
You may not really want to sign out of Google in your browser (as it'll log you out of Gmail, and any other tabs/windows you're using Google apps). When you hit Firebase auth again, it jumps straight into the app (bypassing Google login because it was never really logged out of Google). Instead of logging in immediately, perhaps you want to see the Google account-picker. If so, here's the answer I gave to a related SO question.
Note that the issue you describe will only happen if you've only logged into a single Google/Gmail account, i.e., like you would in incog mode. If you've logged into >1, you'll always get the account-picker so Firebase can tell your app which user you've selected.
basically, firebase logout function logouts the application itself, but does not log out google on the browser.
To log out completely, you need the first sign out of the application then if successful, sign out of Google in the browser.
This then allows users not to log again when they've logged out.
function signoff() {
firebase.auth().signOut().then(function () {
window.alert("you have signed off successfully")
window.location = "https://mail.google.com/mail/u/0/?logout&hl=en";
// document.location.href = "https://www.google.com/accounts/Logout?continue=https://appengine.google.com/_ah/logout?continue=http://localhost/GoogleVue4";
}).catch(function (error) {
console.log(error);
})
}

Web Firebase Google SignIn doesn't work

I am new to web development and am trying to create an app that right now allows you to sign in using Firebase Authentication and the app will display your name. I have been following the Codelab that Firebase offers online to create this basic functionality but I cannot figure out why I am not able to detect that someone has signed in. Here is my initFirebase function:
LoginClient.prototype.initFirebase = 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.
this.auth.onAuthStateChanged(this.onAuthStateChanged.bind(this));
};
Within this I am using onAuthStateChanged to listen for the auth state change and execute the following function that I have written:
LoginClient.prototype.onAuthStateChanged = function(user) {
if(user){
//window.open("userdash.html");
console.log("onAuthStateChanged works")
/*this.userNameDisplay.innerText = "Hello " + user.displayName + "!";
window.alret("Hello " + user.displayName + "!");*/
//this.userNameDisplay.removeAttribute('hidden');
this.userNameDisplay.textContent= user.displayName;
this.userNameDisplay.removeAttribute('hidden');
this.signInButton.setAttribute('hidden', 'true');
this.googleSignInButton.setAttribute('hidden', 'true');
this.createAccountButton.setAttribute('hidden', 'true');
}else{
this.userNameDisplay.setAttribute('hidden', 'true');
this.signInButton.removeAttribute('hidden');
this.googleSignInButton.removeAttribute('hidden');
this.createAccountButton.removeAttribute('hidden');
}
};
The function will detect that there is a user and then display the name of the person who signed in. So what I want to happen is for me to press a button that triggers the following google sign in function:
LoginClient.prototype.googleSignIn = function(){
var provider = new firebase.auth.GoogleAuthProvider();
this.auth.signInWithPopup(provider);
console.log("Signed in google");
};
which will allow a user to signin off the popup window that is created. Once they have successfully signed in, the auth.onAuthStateChanged listener will be triggered and cause the above onAuthStateChanged function to be called. However what is currently happening is that the googleSignIn function is called and a popup window is created but before I can authenticate on the popup window, the page reloads. Once I finish signing in successfully on the popup window the onAuthStateChanged function fails to be called. Can anyone help me figure out why the page reloads when I try to sign in?

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

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.

Categories