Facebook JS SDK FB.Login function - facebook-javascript-sdk

In my website, I have a button for "facebook connect", which when clicked on, triggers the following code:
<script type="text/javascript">
$(document).ready(function(){
console.log(<?=(isLoggedIn()+0)?>);
$("#fbconnect").click( function(){
FB.login(function(response) {
alert(JSON.stringify(response.authResponse));
if (response.authResponse) {
window.location = window.location;
alert('Welcome! Fetching your information.... ');
} else {
alert('User cancelled login or did not fully authorize.');
}
}, {scope: 'email,user_likes'});
} );
});
</script>
The button works well: it shows the facebook login dialog, and then alerts the appropriate message. However, when I refresh the page, the user is still logged out both server-side and client-side. Do I need to handle the access token and cookies myself or does the javascript SDK take care of that? If the latter, then why doesn't this code work?
Thank you.
UPDATE 1:
It works perfectly on localhost with Firefox, and on the server with all browsers. So the problem exists only for chrome and on localhost. Is there some chrome security setting that prevents cookies from being saved for localhost?

Related

why is facebook js sdk web login callback not being called or called too early?

the problems
fb:login-button: with it, I can't log in.
FB.login(): with calling it by clicking a button, I'm able to log in but the callback function called too early before I log in or sign up so passes an unknown state response.
In case of fb:login-button
with facebook logged out, facebook login pop up pops up and when I log in, nothing happens(FB.getLoginStatus returns unknown state).
with facebook logged in, the pop up just flashes away and nothing happens(FB.getLoginStatus returns unknown state).
after both operation, checkLoginState() logs {authResponse: null, status: 'unknown'} neither status: 'not-authorized' or status: 'login'. It means I don't succeed to login I guess. Is that why the buttons onlogin callback is not called? (Cause it's called on login event)
In case of FB.login()
with facebook unknown state, when I click the button, the callback function is called before I login. It results passing unknown state response.
with FB.login() in console, FB.getLoginStatus returns successful login response.
Here is my html code
<body>
<script>
window.fbAsyncInit = function () {
FB.init({
appId: '...',
cookie: true,
xfbml: true,
version: 'v13.0'
});
FB.AppEvents.logPageView();
checkLoginState();
};
function checkLoginState() {
FB.getLoginStatus(function (response) {
statusChangeCallback(response);
});
}
function statusChangeCallback(response) {
console.log(response);
}
(function (d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {
return;
}
js = d.createElement(s);
js.id = id;
js.src = "https://connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
function facebooklogin(){
FB.login(function(response){
statusChangeCallback(response);
});
}
function facebooklogout(){
FB.logout(function(response){
statusChangeCallback(response);
});
}
</script>
<fb:login-button scope="public_profile,email" onlogin="checkLoginState();">
</fb:login-button>
<button onclick="facebooklogin();">fb-login</button>
Any answer would be appreciated.
I found the answer.
The keypoint is FB.logout function leaves a cookie which prevents anymore login attemps. like fblo_51245583...=y.
With the cookie,
if you are logged in facebook and try to login your web then the pop-up will disappear very quickly.
if you are not logged in facebook and try to login your web while the pop-up prompts you to login, the callback function will be called with unknown state response(I guess the logout cookie automatically deny the login attempt at all). and whether you succeed to login in facebook or not it takes no effect on the web.
But I still don't know why the fb:login-button doesn't work.
And when The callback function is still executed earlier than my log-in process.
My goal is
When users log in first time using facebook, they are signed up automatically with their uid value from authResponse.
While they are accepting or loggin in facebook, the callback function should wait until they accept/reject or login/not like event-driven.
But as I understand FB.login functions callback parameter doesn't wait for the action but just wait for a response from the facebook server.
So I need other approaches.
use event subscription refer to https://developers.facebook.com/docs/reference/javascript/FB.Event.subscribe/v13.0

Google OAuth2 SignIn method fires at page load

I have used the official button for Google SignIn:
SignIn Page:
<div class="g-signin2" data-onsuccess="AuthenticateGoogleUser"></div>
function AuthenticateGoogleUser(googleUser){
.....
capture the user info and redirect to Home page
.....
}
When configuring for the credentials, I have set the redirection URL to the signin page.
This is how the Signout happens for the app:
function SignOutGoogleUser() {
if (gapi != null && gapi != undefined &&
gapi.auth2 != null && gapi.auth2 != undefined) {
var auth2 = gapi.auth2.getAuthInstance();
auth2.signOut().then(function () {
auth2.disconnect();
....Redirect to Home page...
});
}
}
The methods work fine. If I signout, will be redirected to home page.
But, when I manually browse the SignIn page after signout, the AuthenticateGoogleUser method is triggered and I am auto signed into the app (with google account).
The AuthenticateGoogleUser method should be only triggered on the button click. Is that right.
But here it is being triggered on load of SignIn page. Is that expected. Can this be stopped.
I'm using MVC C# as backend.
Without seeing all of your code, I am working on the assumption that you have not placed the function in a document ready wrapper and made sure to only kick it off on a button click or other event from which you would like to have it fire. As it stands now, it will fire on that page load.
$(document).ready(function(){
$("btnLogin").click(function(){
AuthenticateGoogleUser(googleUser);
});
});

Facebook Oauth2 cannot manually open the consent dialog Vuejs

I am trying to "Manually Build a Login Flow" according to these docs here: https://developers.facebook.com/docs/facebook-login/manually-build-a-login-flow/
The idea is that i want to generate an one time authorization code, then send it to my back end so it can generate there the access token and then get the user data.
The docs above nicely have sections like "Invoking the Login Dialog and Setting the Redirect URL" and "Exchanging Code for an Access Token" along with the respective endpoints to hit, which is exactly what i want. So I started implementing the dialog invocation on the front end which is a vuejs app, so i can generate the authorization code to send it to my server.
Here is the code:
<script>
import axios from "axios";
export default {
methods: {
facebookAuth(){
axios.get('https://www.facebook.com/v4.0/dialog/oauth?client_id=MY_CLIENT_ID&redirect_uri=http://localhost:3000&state="I AM A STRING"', {
headers:{
'Access-Control-Allow-Origin': '*',
}
})
.then(res=>{
console.log(res);
})
}
}
};
</script>
The first issue here is that i get CORS error, even with my anticors chrome extension open. So i pass it to this proxy https://cors-anywhere.herokuapp.com/
and I manage to make it work, but no consent dialog opens. I just get a http response with an html page code as a response body.

Facebook JS sdk Oauth onload

I trye to use Facebook JS SDK and I fell on a problem.
I want that after the page load, the user click on the FB button, and then,
if he is already logged I change location,
if not,
it trigger the fb loggin popup
here is my code "
window.fbAsyncInit = function() {
// init the FB JS SDK
FB.init({
appId : '<?php echo $action->appId; ?>', // App ID from the app dashboard
status : true, // Check Facebook Login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // Look for social plugins on the page
});
FB.Event.subscribe('auth.authResponseChange', function(response) {
if (response.status === 'connected') {
$(location).attr('href','nexPage.php');
} else if (response.status === 'not_authorized') {
FB.login();
} else {
FB.login();
}
});
My problem come with the fact that the facebook authResponseChange trigger onload so if the user is already logged and just arrive on the page he is directly send to the next page, and I don't want that !
I want the user to see the page first, click, then login/or not and go to the next page
Does somebody have an idea how to do that ?
(and no click event possible cause after the user logged, FB reload the page)
found !
put the status to false
FB.init({
appId : '<?php echo $action->appId; ?>', // App ID from the app dashboard
status : false, // Check Facebook Login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // Look for social plugins on the page
});
Sorry for disturb

Why won't CasperJS accept a redirect request after clicking on a link?

I'm having more Casper troubles, this time I've told Casper to click on a href that will redirect it to a page that will redirect it to the twitter app auth page:
var casper = require('casper').create({
verbose: false,
logLevel: 'debug',
waitTimeout: 10000
});
phantom.cookiesEnabled = true;
casper.start('http://foo.bar', function afterstart() {
if (this.exists('#back-to-top')) {
this.echo('BOOYA! foo.bar is loaded', 'INFO');
} else {
this.echo('Page didnt load, something went all screwy.', 'ERROR');
}
});
casper.then(function signin() {
this.click('a[href="/sys/login"]' );
});
casper.then(function tellsignin() {
if (this.exists('#not-logged-in ')) {
this.echo("I clicked on twitter login button, so now the twitter login page is loaded.", 'INFO');
} else {
this.echo('Twitter login link didnt work, something went wacky');
};
});
When I run it, the console error output is this, plus some other stuff that isn't important:
Test file: testingtest.js
BOOYA! foo.bar is loaded
Twitter login link didnt work, something went wacky
I've tried looking up explanations, and found this group thread, but it unfortunately doesn't provide any answers for my problem.
Does anyone know any possible reasons why Casper isn't redirecting?
I've resolved the issue thanks to all of your help and support, lol! What happened is that the tellsignin function was being executed before the browser had time to be redirected to the twitter app auth page, so I just added a this.waitForText('Authorize foo-bar app to use your account?') to the signin function.