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");
}
});
Related
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.
}
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 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.
I'm pulling album photos from Facebook API and then arranging them in masonry style. I have it set up so that I'll run the API function, then when I click a button it'll run the masonry function, which works fine. Now what I want to do is have the masonry run automatically after all the images are downloaded, like so:
function fbAPI() {
//downloading photos and placing them in a div
masonryFunction();
}
function masonryFunction(){
//run the masonry plugin
}
The trouble I run into though is masonryFunction runs well before fbAPI has finished doing it's thing, which prevents it from working (all the photos must be loaded up first). Now I can't simply have masonryFunction run when the page is loaded because fbAPI doesn't get launched until after some user input. What can I do?
Call the fbAPI() function in the callback function for the FB login function.
For example,
FB.login(function(response) {
if (response.authResponse) {
facebookLoggedIn();
} else {
alert('User cancelled login or did not fully authorize.');
}
});
function facebookLoggedIn() {
fbAPI();
}
Or, subscribe to FB auth.statusChange event:
FB.Event.subscribe('auth.statusChange', function(response) {
facebookStatusChange(response);
});
function facebookStatusChange(response) {
if (response.status === 'connected') {
uid = response.authResponse.userID;
accessToken = response.authResponse.accessToken;
facebookLoggedIn();
} else if (response.status === 'not_authorized') {
// the user is logged in to Facebook,
// but has not authenticated your app
} else {
// the user isn't logged in to Facebook.
}
}
I'm trying to get the users permission if they haven't granted the publish_stream permission.
I have this function:
function AskPermission()
{
ResizeUnity(0);
FB.login(function(response)
{
alert("Hit");
if (response.authResponse)
{
alert('Granted!');
GetUnity().SendMessage("POST", "POST", "Granted");
}
else
{
alert('User cancelled login or did not fully authorize.');
GetUnity().SendMessage("POST", "POST", "");
}
ResizeUnity(1);
}, {scope: 'publish_stream'});
}
When it's called a small window pops up asking .... would like to access your public profile and friends list. There's 2 buttons Okay and cancel. When Okay is pressed it goes on to another screen asking .... would like to post to your friends on your behalf. Again 2 button, Okay and Skip.
When I press the first skip denying all permissions it doesn't return anything. the alert("Hit"); is not called.
When I do press Okay on the first prompt it goes on to the second popup and asks about the posting on behalf. I press Okay, the alert 'Granted' is called.
When I press skip the alert 'Granted' is also called even though I hit skip.
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
// the user is logged in and has authenticated your
// app, and response.authResponse supplies
// the user's ID, a valid access token, a signed
// request, and the time the access token
// and signed request each expire
var uid = response.authResponse.userID;
var accessToken = response.authResponse.accessToken;
} else if (response.status === 'not_authorized'){
// the user is logged in to Facebook,
// but has not authenticated your app
} else {
// the user isn't logged in to Facebook.
}
});
Use this Facebook function to check whether user grant permissions or not.
You can recall same function if user not permitted your app. For more assistance in code, I can help you. :)
For more information see :Fb.getLoginStatus
Maybe this is happening because you are trying to open Facebook login in a popup but it opens in the same window where you called fb.login. When you click Cancel, Facebook tries to close the window, but as it wasn't opened by facebook the window won't close. It never tries to follow the callback url.
Try using in the config {display: "touch"} or {display: "page"} like this:
function AskPermission()
{ResizeUnity(0);
FB.login(function(response)
{
alert("Hit");
if (response.authResponse)
{
alert('Granted!');
GetUnity().SendMessage("POST", "POST", "Granted");
}
else
{
alert('User cancelled login or did not fully authorize.');
GetUnity().SendMessage("POST", "POST", "");
}
ResizeUnity(1);
}, {scope: 'publish_stream', display: 'page'});
}
Is there a reason why not to ask for all the permissions to need in one screen itself. Howevern, keep in mind that as per facebook documentation, ask few permissions to begin with and then keep increasing the permissions request on the go.
https://developers.facebook.com/docs/reference/login/#permissions
Try this code
FB.login(function(response) {
if (response.authResponse) {
var access_token = FB.getAuthResponse()['accessToken'];
console.log('Access Token = '+ access_token);
FB.api('/me', function(response) {
console.log('Good to see you, ' + response.name + '.');
});
} else {
console.log('User cancelled login or did not fully authorize.');
}
}, {scope: ''});
Hope that helps