Issue when using firebase.auth().onAuthStateChanged accross two pages - javascript

I am having a small problem with two html pages which used to work in the past.
First, I have a login page (login.html) containing this kind of code:
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
window.open("main.html",'_self');
} else {
// No user is signed in.
prompt for login ....
......
}
});
Second, I also have this page (main.html) containing this sort of code:
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
do serious work ....
......
} else {
// Let us double check:
let theUser = firebase.auth().currentUser;
if (!theUser) {
// No user is signed in.
window.open("login.html",'_self');
}
// We need some patience :)
......
}
});
Once a user is logged in, things are supposed to go to main.html; and this is how it used to work. But now, for some unknown reason; when I log in, even though I have provided my credentials, the flow goes to main.html (as it should) but immediately bounces back to login.html.
I have been able to check that the block (in the main.html):
firebase.auth().onAuthStateChanged(function(user) {...}
does not detect me as logged in. Why is that?
P.S.
I have verified that my domain is added in the list of Authorized domains in the Firebase console.

I am encountering the same issue. I narrowed it down to Chrome. It seems to think that Chrome isn't allowed to save cookies when it is (I checked the settings). Might be an issue with a recent Chrome update? Just as a sanity check, try it on Firefox and let me know if that works. It did for me.
UPDATE: This is what I get back when I console log the error
{code: "auth/web-storage-unsupported", message: "This browser is not
supported or 3rd party cookies and data may be disabled.", a: null}
UPDATE 2: Strangely enough, I disabled cookies, tried and it failed. Re-allowed cookies (just as it was initially) and it works now. I would suggest capturing this error and prompting users to ensure they check their browser settings. I'm going to do this in my app.

Related

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.

how to get if person is already liked fb page or not using javascript sdk

I intergrate like button in my website. After login with facebook, now if any one already liked fb page directly from facebook then some fields will be shown to user otherwise fields will be hidden. I already put function for above thing and it works for me but not for others. Don't know why?
Here is a function which contains fb like thing and triggered on button click
function getUserDetail(){
FB.api("me/likes/242500342443159", function(response) {
if ( response.data.length == 1 ) {
$('#myModal').modal('show');
getUserInfo();
document.getElementById("note").style.display="none";
console.log('You like it');
} else {
$('#myModal').modal('show');
getUserInfo();
document.getElementById("form").style.display="none";
console.log("You don't like it");
}
});
}
and i also took user_likes permission on login.
Please correct me if i am doing any mistake in above function.
IMPORTANT: You are not allowed to hide/gate content behind a like or incentivize liking a Page in any way. you must read the platform policy before creating any App: https://developers.facebook.com/policy/
That being said, you would need user_likes for that API call, which needs to get reviewed by Facebook before everyone can use it. Without review, only users with a role in the App are able to authorize that permission. It is called Login Review: https://developers.facebook.com/docs/facebook-login/review
If you got permission for your application, and got premission from the logged in user, but it still doesn't work I would sugest creating error handling and in case of debugging log the response object.
Check for error codes and response format: https://developers.facebook.com/docs/graph-api/reference/user/likes/

Having an hard issues with google and his API or login buttons

I followed the documentation from them and i don't see what is my error from my part !
I'm trying to get the information from the profile of the user (which could be the name gender etc etc...)
And i followed all the steps from google website (in my case, the javascript code)
Everything works, less that request which i want to do to the user profile!
This example is the callback function after logging to the google account which is automatically executed:
function signinCallback(authResult) {
if (authResult['status']['signed_in']) {
// Update the app to reflect a signed in user
// Hide the sign-in button now that the user is authorized, for example:
//document.getElementById('signinButton').setAttribute('style', 'display: none');
console.log(authResult);
gapi.client.setApiKey('API_KEY'); //(That function gaves me an error which is invalid credentials, i did put my API_KEY (from the google console ))
gapi.client.load('plus','v1', function(){
var request = gapi.client.plus.people.get({
'userId': 'me'
});
request.execute(function(resp) {
console.log(resp);
//console.log('Retrieved profile for:' + resp.displayName);
});
});
gapi.auth.signOut(); // logging out !
} else {
// Update the app to reflect a signed out user
// Possible error values:
// "user_signed_out" - User is signed-out
// "access_denied" - User denied access to your app
// "immediate_failed" - Could not automatically log in the user
console.log('Sign-in state: ' + authResult['error']);
}
}
Everything works less than setAPIkeys and everything below !
If i don't put the set function and the code below, i receive an 400 error ("message": "Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup.").
So i'm losing hope in doing that sincerely ... i think that google's documentation is awful !
What's wrong with that?
Merry christmas to everyone !
P.S. : yeah i know that the API key musn't be hard coded, but i'm so lost with the documentation from google sincerely ...
Possible solutions:
Try removing
gapi.client.setApiKey('API_KEY');
and
gapi.auth.signOut(); // logging out !
signOut works very fast, while gapi.client.load is asynchronous function which loads js code. User is probably signed out before gapi.client.load callback is executed.
I'm not sure if that's required:
Go to the Google Developers Console.
Select your project.
In the sidebar on the left, select APIs & auth.
In the displayed list of APIs, find the Google+ API and set its status to ON.
Make sure you're requesting scope https://www.googleapis.com/auth/plus.login or https://www.googleapis.com/auth/plus.me while signing in.

FB.logout() - no access token - "Log in as Different User"

This question is in relation to this question: FB.logout() called without an access token
I had a question i was hoping someone could help with.
I get everything in the link above, but how do you handle when someone uses a public computer and leaves themselves logged in to FB by accident? Then a new user tries to log in to an app, but it is not them. I want to have a button to log them out of FB altogether to "log in as a different user".
I cannot do that until they authorize the app, right? So they need to authorize the app under someone else's account and then log out? There has to be another way.
Any feedback would be great - tried searching for a while on this, but to no avail. I might be over thinking it, but there should be some way to "log in as a different user".
You can do something like:
FB.getLoginStatus(function(response) {
if (response.status === "connected") {
FB.api("me", function(response2) {
// notify the user he is logged in as response2.name, and if it's not him call FB.logout
}
}
else {
// prompt the user to login
}
}
Modify your logout to something like this :-
function logout(response){
console.log("From logout" + response);
if(!response.authResponse){
window.location = "/web/login/";
return;
}
FB.logout(function(response){
FB.Auth.setAuthResponse(null,'unknown');
logout();
});
}
i.e keep on sending logout request to Facebook till the actual logout happens.
Try to use Session and save the user's ID in that session.
You can control the expiration time of that session( by default its 20 minute if the user doesn't have any activity on the page)
then in each page Load even check whether the season is still active for that user or not.
page Load event:
if(Session["LoggedIn"]==null)
{
Response.Redirect("~/Login.aspx");
}
This code above will redirect user to login page of your website if the session has expired.

Facebook Connect Publish Stream JS Help

My site allow users to login via Facebook Connect and also allows them to update a status field our site. I want to include a checkbox below the status update field that will allow them to post this update to their Facebook profile as well if they so choose. In order to do this I need the user to grant our application permissions to post to their Facebook profile which is supported by prompting the user for 'publish_stream' permission using the JS function FB.Connect.showPermissionDialog http://developers.facebook.com/docs/?u=facebook.jslib.FB.Connect.showPermissionDialog.
The problem I'm having is figuring out if I need to prompt the user to do this. Basically the user experience I'd like to have is that when the user checks this box for the first time I want them to be prompted to grant this permission. Once that has been granted I won't need to prompt them in the future if they check that box again. I can't seem to figure out what JS to include in the onclick action of that checkbox that will check to see if the user has granted this permission and if not then prompt them, otherwise do nothing. Also after checking the box and granting the permission I want to do nothing (no page reload) but if they reject the request to grant permission I'd like the checkbox to be unchecked. I think I may need to use the FB.ApiClient.users_hasAppPermission JS function http://developers.facebook.com/docs/?u=facebook.jslib.FB.ApiClient.users_hasAppPermission but am still confused on what this would look like. The psuedo code for this would be:
onclick="
if(user_already_granted_permission) { do_nothing; }
else {
prompt_user_to_grant_permission {
wait_for_response_from_permission_dialog {
if(permission_granted) { do_nothing; }
else { uncheck_checkbox; }
}
}
}
"
One other thing worth noting is that I've already verified the user is logged in through Facebook Connect when the page was rendered. I'm hoping someone else using Facebook Connect has already been able to figure this one out. Thanks in advance for your help!
I recently developed an online demo that uses Facebook Connect and gets the friend list of a given user - it's not the same as your case, but I used FB.Facebook.apiClient.requireLogin to get the user logged, like this:
var api_key = 'd04fba62ff27c6c84a6b767d404bcec3';
var channel_path = '/xd_receiver.htm';
/* initialize facebook API */
FB_RequireFeatures(['Api'], function() {
FB.Facebook.init(api_key, channel_path);
var api = FB.Facebook.apiClient;
api.requireLogin(function(exception){
// user is logged in and my application
// has permissions to get friend list
});
});
You can do something like this:
FB.Facebook.apiClient.users_hasAppPermission('publish_stream', function(has_perms) {
if(has_perms) {
// User has granted the publish_stream permission
} else {
// User has not granted the publish_stream permission
}
});
The second param for the users_hasAppPermission function is a callback which returns the result of the check.

Categories