I have the following JavaScript code and the page just keep refreshing. It is just how it sounds like, I have my console open in order to see which console.log() is used. I see Not logged and then it refreshes the page then again displays Not logged and refreshes and goes in a loop. I read that onAuthStateChanged() is called when a state change occurs and until a page is completely refreshed the state changes a couple of times.
How should I proceed in case I just want to redirect user in case he is not logged in?
firebase.auth().onAuthStateChanged((user) => {
let everyHeaderUsername = document.getElementsByClassName("user-header-username");
if (user) {
console.log("Logged");
for (let i = 0; i < everyHeaderUsername.length; i++) {
everyHeaderUsername[i].textContent = `${user.displayName}`;
}
} else {
console.log("Not Logged");
for (let i = 0; i < everyHeaderUsername.length; i++) {
everyHeaderUsername[i].textContent = "Sign in";
}
console.log("Not logged in");
window.location.href = "index.html";
}
});
I think In your else condition. You are doing:
window.location.href = "index.html";
So when the page is initially loaded. The state onAuthStateChanged runs and user is not found so the page gets updated. And the cycle repeats.
What do you mean with keep refreshing? And yes, onAuthStateChanged() is called after an authentication state change.
But for simplicity I would go with the following code:
var user = firebase.auth().currentUser;
if (user) {
// User is signed in.
} else {
// No user is signed in.
}
Related
I am using Facebook API to log in a user. It logs in a user successfully.
But whenever I refresh the website or close it then reopen it logs out automatically. I don't need that I want a user logged in until he himself logs out of my website. How do I do it?
This is my code:
function statusChangeCallback(response) {
if (response.status === 'connected') {
setElements(true);
console.log('Logged in');
instaInfo();
} else {
setElements(false);
console.log('not logged in');
}
}
function checkLoginState() {
FB.getLoginStatus(function(response) {
statusChangeCallback(response);
});
}
function setElements(isLoggedIn) {
if (isLoggedIn) {
document.querySelector('#fb-btn').style.display = 'none';
document.querySelector('.logout').style.display = 'block';
document.querySelector('.navigation').style.display = 'block';
document.querySelector('.nav-main').style.visibility = 'visible';
document.querySelector('#container').style.display = 'block';
} else {
document.querySelector('#fb-btn').style.display = 'block';
document.querySelector('.logout').style.display = 'none';
document.querySelector('.navigation').style.display = 'none';
document.querySelector('.nav-main').style.visibility = 'hidden';
document.querySelector('#container').style.display = 'none';
}
}
document.querySelector('.logout').addEventListener('click', () => {
FB.logout(function() {
setElements(false);
console.log('Logged Out!');
});
});
According to the facebook documentation:
While you can call FB.getLoginStatus any time (for example, when the
user tries to take a social action), most social apps need to know the
user's status as soon as possible after the page loads. In this case,
rather than calling FB.getLoginStatus explicitly, it is possible to
check the user's status by setting status: true when you call FB.init.
To receive the response of this call, you must subscribe to the
auth.statusChange event. The response object passed by this event is
identical to that which would be returned by calling FB.getLoginStatus
explicitly.
https://developers.facebook.com/docs/reference/javascript/FB.getLoginStatus/
It might just be that you're running into a problem with the asynchronous nature of javascript in your code example. Have you checked what your call on getLoginStatus actually returns?
You can take advantage of the browser's localStorage (it' s a method of the window object) to keep the data even after reloading the page or even after closing the window.
Take a look here: https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
On my multi-page HTML website (hosted by Firebase), I have a sign in/out button. Whenever I press sign out, the sign out button becomes the sign in button, thanks to my CSS, and the console reports "user not logged in".
However, when I reload the page or navigate to a different one (Ctrl+R and Ctrl+Shift+R make no difference), the sign out button reappears, and the console reports "user logged in", as if the server doesn't remember the user should be signed out, and not automatically signed in after the page reloads.
Here's what I use for sign in. Note that setButtons() is my code to change the CSS to show what button I need to. gLogin() is called when the Sign In button is pressed, and gLogout is called when the Sign Out button is pressed.
var signedIn;
var curUser = null;
function updateUser(user)
{
if (user) {
curUser = user;
signedIn = true;
console.log("User is logged in");
// User is signed in.
} else {
curUser = null;
signedIn = false;
console.log("User is not logged in");
// No user is signed in.
}
setButtons(signedIn);
}
firebase.auth().onAuthStateChanged(updateUser);
function gLogin() {
firebase.auth().signInWithPopup(gProvider).then(function (result) {
var token = result.credential.accessToken;
var user = result.user;
signedIn = true;
location.reload(true);
}).catch(function (error) {
console.log(error);
});
}
function gLogout() {
firebase.auth().signOut().then(function () {
signedIn = false;
updateUser(null);
}).catch(function (error) {
console.log(error);
});
}
I figured it out: Apparently, the issue was that I didn't set a default auth persistence state. From what I understand, this meant that persistence would have undocumented behavior. Here's what I added to each of my pages' scripts:
firebase.auth()
.setPersistence(firebase.auth.Auth.Persistence.SESSION)
.then(function() {
console.log("Persistence set");
}).catch(function(error) {
console.log(error);
});
I have a page with side bar,as soon as i login it works fine.. But if i close tab and open again this error comes "Cannot read property 'view_permission' of undefined", and the side bar will have no contents in it. If i change company or login again it works fine. Here i had written code to redirect to login page but when error occurs, it redirects to login page and within fraction of seconds it again redirects to main page.
I am here by sharing my code of ts please help,
ts code:
var page_permision = user.access;
var url = this.router.url.split('/');
var goBack = page_permision.filter(function(page) {
if(page.viewName == url[1]) {
return page;
}
})
if((!goBack) || (!goBack[0].view_permission)) {
this.router.navigate(['/routes']);
}
Please Help.
Thank You
you can add a check of undefined to avoid this error on same line, insted of checking it's length, if page_permision length is 0 loop will not run because of condition mentioned in loop i < page_permision.length.
if(typeof page_permision != "undefined") {
for(let i = 0; i < page_permision.length ; i++) {
var name = page_permision[i].viewName;
this.obj[name] = page_permision[i].view_permission;
}
} else {
this.router.navigate(['/login']);
}
So me and my group are trying to make a website where the user has to sign up and login and they will go to a new html page and it checks whether the user is logged on or not, We're using firebase and we don't know why the page keeps on refreshing constantly.. this is our code below.
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
console.log("Logged in");
window.location.href = "home.html";
return false;
}
else {
console.log("Not Logged in");
}
});
I have the following code in the load function of my app:
var token = window.localStorage.getItem("LOCAL_TOKEN_KEY");
if (!token) {
$window.location = 'login.html';
}
else {
$window.location = 'index.html';
}
I am trying to redirect the user based on whether or not they have logged in before by checking if the user has a token stored. By putting this in the load function of the app, it causes an infinite loop because when I redirect, it checks again and again..
So how is this typically handled? I haven't figured out a way to skip the login page if the user has a token.
Add the following code to a controller on the page (not the onload event):
if (!token) {
if ($window.location === 'login.html') {
return;
}
else
{
$window.location = 'login.html';
}
} else {
$window.location = 'index.html';
}
This way if they are already on the login page it will not redirect them.