Persist login on Firebase with Google Sign-in? - javascript

I'm currently using Firebase such that users sign in with their Google accounts to access the app. However, closing the page/opening the page in a new tab requires the user to sign in again. Is there a way to prevent users from having to re-login?
Here is the login code I am using (the example from the firebase docs)
function firebaseLogin() {
firebase.auth().signInWithPopup(provider).then(function(result) {
var token = result.credential.accessToken;
var user = result.user;
document.getElementById('user-name').innerHTML = user.displayName;
document.getElementById('propic').src = user.photoURL;
addClass(login, 'hidden');
removeClass(logout, 'hidden');
var snackbarData = {
message: 'Login Successful',
timeout: 2000
};
snackbarContainer.MaterialSnackbar.showSnackbar(snackbarData);
console.log(user);
reloadList();
}).catch(function(error) {
var errorCode = error.code;
var errorMessage = error.message;
var email = error.email;
var credential = error.credential;
var snackbarData = {
message: 'Login Unsuccessful',
timeout: 2000
};
snackbarContainer.MaterialSnackbar.showSnackbar(snackbarData);
console.error(error);
});
}

I'm not sure if this is the official way to do it, but I ended up saving the user returned from firebase.auth().currentUser in localStorage, and then checking if a user could be found in localStorage on document load. If a user is found, I just set firebase.auth().currentUser to equal the user from localStorage, and everything seemed to work as intended. (For example, if there wasn't an authenticated user, the client wouldn't be able to make calls to the database, but setting currentUser in this fashion allowed accessing the database.)

Related

Firebase saying user is null after successful login

I'm trying to upload my user's files to a bucket connected to their uid. So, in order to do it I try to grab their uid from the following code in my upload.js file:
const uploader = document.getElementById("uploader");
const fileButton = document.getElementById("fileButton");
fileButton.addEventListener('change', function(e)
{
// Get file
var file = e.target.files[0];
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
console.log("state = definitely signed in");
firebase.storage().ref('users').child(user.uid + "designs").put(file);
} else {
// No user is signed in.
console.log("state = definitely signed out");
}
});
});
Even after the user is logged in and the it directs them to the new page I always get informed that they aren't signed in. Should I use information from the session cookie instead? Any help would be appreciated!
After a few days I realised that I wasn't calling the id token correlated with the user that is logged in. This solved it:
firebase.auth().onAuthStateChanged(function(user)
{
if (user)
{
// User is signed in.
console.log(user);
user.getIdToken().then(function(idToken)
{ // <------ Check this line
console.log(idToken); // It shows the Firebase token now
});
console.log(user.uid);
firebase.storage().ref('users').child(user.uid + "/designs").put(file);
}
else
{
// No user is signed in.
console.log("state = definitely signed out");
}
});

Why doesn't firebase javascript authentication work with ie11?

I have implemented google authentication on a web page using firebase sdk.
It works fine on chrome, firefox and edge, but on ie11 I get a google authentication page but the authenticated user information is always null.
I think it's supported in ie 11.
firebase.google.com/support/guides/environments_js-sdk
I added the polyfill by cdn and executed it but it doesn't work. User information is still null.
unpkg.com/core-js-bundle#3.0.1/minified.js
Why doesn't it only work with ie11?
*function signInGoogle() {
if (!firebase.auth().currentUser) {
var provider = new firebase.auth.GoogleAuthProvider();
provider.addScope('https://www.googleapis.com/auth/plus.login');
firebase.auth().signInWithRedirect(provider);
} else {
firebase.auth().signOut();
}
}
function initApp() {
firebase.auth().getRedirectResult().then(function (result) {
var user = result.user;
console.log(user); // always null
if (user) {
document.getElementById('createForm').submit();
}
}).catch(function (error) {
var errorCode = error.code;
var errorMessage = error.message;
var email = error.email;
var credential = error.credential;
// [START_EXCLUDE]
if (errorCode === 'auth/account-exists-with-different-credential') {
alert('You have already signed up with a different auth provider for that email.');
} else {
console.error(error);
}
});
}*
In order to reduce the SDK size, Firebase no longer ship the Polyfils that are required for some older browsers. This was one of the changes in the 6.x release.
Please take a look at https://firebase.google.com/support/guides/environments_js-sdk how to manually enable Polyfills as required.

firebase google authentication in web does not work on android app webview

I am creating a website that has login with firebase google authentication. It's working fine in all browsers. But when I add this website in my app as webview it does not work.
website showing this error:
This operation is not supported in the environment this application is running on. "location.protocol" must be http, https or chrome-extension and web storage must be enabled.
here some code bellow:
javascript code:
function login(){
console.log('login called');
function newLoginHappend(user){
if(user){
model_questions(user);
}else{
var provider = new firebase.auth.GoogleAuthProvider();
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;
// ...
}).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;
// ...
});
}
}
firebase.auth().onAuthStateChanged(newLoginHappend);
}
window.onload = login();
webview code:
WebSettings webSettings =webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webView.setWebViewClient(new WebViewClient());
webView.loadUrl("https://mahmud-cse16.github.io/CBAP_Handout/");
Is there any way or technique to solve this problem?? if you have any idea then share with us please.
thanks
Try enabling DOM Storage for the webview
WebSettings webSettings = myWebView.getSettings();
webSettings.setDomStorageEnabled(true); // localStorage
Sets whether the DOM storage API is enabled. The default value is false.
Android Developer Reference
To get around "disallowed_useragent" error, one way is to use the Android Google Auth SDK to log in natively in the app, and then pass the Google token to the Webview so Firebase can use it with auth.signInWithCredential().
It might work for other providers but here's how I did it with Google auth on Android:
Android:
val gso =
GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(clientId)
.requestEmail()
.build()
val googleSignInClient = GoogleSignIn.getClient(activity, gso)
activity.startActivityForResult(
googleSignInClient.signInIntent,
object : ActivityWithResultListener.OnActivityResultListener {
override fun onActivityResult(resultCode: Int, data: Intent?) {
if (data != null) {
val credential = GoogleAuthProvider.getCredential(account.idToken!!, null)
idToken = account.idToken!!
// Then pass the token to your webview via a JS interface
}
}
}
)
Web:
const idTokenFromApp = AndroidBridge.getAuthToken(); // This is the idToken from the Android code above
if (idTokenFromApp) {
// from https://firebase.google.com/docs/auth/web/google-signin
// Build Firebase credential with the Google ID token.
// https://firebase.google.com/docs/reference/js/v8/firebase.auth.GoogleAuthProvider#static-credential
const credential = firebase.auth.GoogleAuthProvider.credential(idTokenFromApp);
// Sign in with credential from the Google user.
firebase.auth.signInWithCredential(credential).catch((error) => {
// Handle Errors here.
const errorCode = error.code;
const errorMessage = error.message;
logError(`Error logging in: ${errorCode} ${errorMessage} token: ${idTokenFromApp}`, error);
});
}

I am unable to login using signInWithEmailAndPassword(email,password) in firebase

When I am logging in using web page the user is not signing in.I am actually working on firebase using javascript.If I am running same code through other project then it is working fine.
var google = document.getElementById("google_sign")
var facebook = document.getElementById("facebook_sign")
var linked = document.getElementById("linked_sign")
var login = document.getElementById("login_btn");
var email1 = document.getElementById("email")
var password1 = document.getElementById("password")
login.onclick=function login1(){
email = email1.value;
password = password1.value;
firebase.auth().signInWithEmailAndPassword(email,password)
.then(() => window.location.href = 'part-after-login.html')
.catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
console.log(error.Message);
});
}

firebase add user to realtime database upon sign up (javascript)

I'd need to create a users main node, that will have as child users id created upon sign up, as well as child elements dynamically populated later on (empty for now).
so my db would look like:
- users
- uid
- lists
- list name
- content
- uid
- uid
...
I'm still at the beginning and for now i'm trying to put the user id inside - users but doesn't work, the code (EDITED):
var refUsers = database.ref('users');
// Add sign up event
btnSignup.addEventListener('click', e => {
// to do: check for real email
const email = txtEmail.value;
const pass = txtPassword.value;
const auth = firebase.auth();
// Sign in
auth.createUserWithEmailAndPassword(email, pass)
.then(function success(userData){
var uid = userData.uid;
refUsers.push(uid);
})
.catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
alert('Error: ' + errorMessage);
});
});
I also didn't understand if i should manually or programmatically create the main - users node inside the database, how (since it asks me for a value too) so for now i didn't create it at all, the documentation lack of many stuff imo.
The functionality you're describing can be achieved using Firebase Authentication Triggers.
ie.
const database = firebase.database()
const createUser = user => database.ref().child(`User/${user.uid}`).set(user)
exports.createUser = functions.auth.user().onCreate(createUser)

Categories