I'm using Facebook Auth and I'm trying to add an automatic redirect from interior pages to the log in page if the user is not logged in or they haven't authorized my app, and that part works fine. The problem I'm having is that when you arrive on index.php, it redirects you to index.php again, and again, infinitely. I've tried numerous things, like if (location.href == "index.php") do nothing, else redirect, but nothing I try works.
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
var uid = response.authResponse.userID;
var accessToken = response.authResponse.accessToken;
} else if (response.status === 'not_authorized') {
window.location = "index.php";
} else {
window.location = "index.php";
}
});
Related
In my website, when the visitor visit my web, if they have not liked my facebook page yet, i want to show Iframe like box.
I have seen many code in the web as well as in stackoverflow, but it seem doesn't work well. Here is my javascript code:
$(document).ready(function(){
FB.init({
appId : 'IDAPP',
status : true,
cookie : true,
xfbml : true
});
FB.getLoginStatus(function(response) {
if (response.status == 'connected') {
var user_id = response.authResponse.userID;
var page_id = "PAGE_ID";
var fql_query = "SELECT uid FROM page_fan WHERE page_id =" + page_id + " and uid =" + user_id;
var the_query = FB.Data.query(fql_query);
the_query.wait(function(rows) {
alert(rows);
if (rows.length == 1 && rows[0].uid == user_id) {
alert("like");
} else {
alert("not like");
}
});
} else if (response.status === 'not_authorized') {
alert("not authorized");
} else {
alert("not login");
}
});
});
Request with login or not login or not_authorize it work well, but when check for page is like or note, it doesn't run anything.
FQL is deprecated, and you would need to authorize a user with the user_likes permission - after that, it´s just a call to the /me/likes endpoint. You will not get that permission approved for like gating, because that´s not allowed. And you will not get it approved for "please like my page" overlays/iframes either :) - because the user does not benefit from that overlay in any way, it is only annoying.
There is only one possible way:
Subscribe to the like event: https://developers.facebook.com/docs/reference/javascript/FB.Event.subscribe/
In the event callback, store a cookie so next time the user visits your page you don´t show the overlay/iframe anymore
Problem is, you don´t get the information if the liked or unliked something. And the user could just clear his cookies, so you can never be sure. My advice: don´t annoy your users with it.
I redirect to the main page during 2 scenarios
While the user hits logout
The session expires...
Logout functionality code...
$("#logoutLink").click(Logout);
function Logout() {
$.post("Logout",
{ antiCSRF: '{{acsrf}}',
session_id: '{{session_id}}'
});
alert("You are now securely logged out.");
window.location = './';
}
Session expiration code
function checksession() {
$.post("CheckSession",
{ antiCSRF : '{{acsrf}}',
session_id: '{{session_id}}'
},validateresult).fail(function() {alert("Session check failed")})
}
function validateresult(result){
if (result == "N"){
valid_flag = "N"
alert("Your session has been timed-out. Please click OK to be redirected to the login page to start a new session.");
window.location = './';
}
else { valid_flag = "Y";
return valid_flag
}
}
In the first case ie; when I hit the logout button the page is redirected to the main page without any issues...
But the code that gets executed during the ajax call does not work..ie; window.location is not working..
Not sure what is the difference between the
The ajax call is asynchronous. You should show the alert() and perform the redirection in the callback function which is executed once the $.post() finishes:
$("#logoutLink").click(Logout);
function Logout() {
$.post("Logout", {antiCSRF: '{{acsrf}}', session_id: '{{session_id}}'}, function() {
alert("You are now securely logged out.");
window.location = './';
});
}
I need to fire my server side code after calling the FB.logout from Facebook JS sdk. Here's how my html looks
<asp:LinkButton ID="lbtnSignOut" runat="server" Text="Sign Out" OnClientClick="return Logout();" OnClick="lbtnSignOut_Click"></asp:LinkButton>
and the js code
function Logout() {
var currentToken = "<%= Session["AccessToken"]%>";
if (currentToken != null && currentToken != '') {
FB.logout(function (response) {
});
}
return true;
}
and subsequently in the server side code, i clear out all application specific session and signs the user out using FormsAuthentication sign out call and redirect to different page.
Now the problem is, the moment I return true from the js function, the server side code fires without waiting for fb.logout to complete the call and the user token does not expire and user is automatically logged back in the FB.Event.subscribe('auth.authResponseChange', function (response) {}; call in the page load which i have picked from standard code.
FB.Event.subscribe('auth.authResponseChange', function (response) {
if (response.status === 'connected') {
//SUCCESS
//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 currentToken = "<%= Session["AccessToken"] %>";
if (currentToken == null || currentToken == '') {
// Handle the access token
// Do a post to the server to finish the logon
// This is a form post since we don't want to use AJAX
var accessToken = response.authResponse.accessToken;
var form = document.createElement("form");
form.setAttribute("method", 'post');
form.setAttribute("action", '/facebookLogin.ashx');
var field = document.createElement("input");
field.setAttribute("type", "hidden");
field.setAttribute("name", 'AccessToken');
field.setAttribute("value", accessToken);
form.appendChild(field);
document.body.appendChild(form);
form.submit();
}
}
else if (response.status === 'not_authorized') {
//FAILED
console.log('User cancelled login or did not fully authorize.');
}
else {
//UNKNOWN ERROR
console.log('Logged Out.');
}
});
};
while if i set the value to false, user is logged out from facebook but my custom code does not fire.
So my question is how to call the server side code after the facebook js sdk logout code has fired?
Any help or pointers will be much appreciated!!!
Paritosh
Put the return true inside the function(response){} block, so that is only called when the FB.logout call returns
I am using Javascript sdk with a facebook app to create login page for user.
FB.login prompts the user to enter facebook username and password. I have saved all the info such as user_id, Access_token, and all info. However, when the user logout. I want to login to facebook without the need to re-enter username and password again. i want to use the user-id and access token to login directly using the javascript API.
Thanks
function updateButton(response) {
button = document.getElementById('fb-auth');
userInfo = document.getElementById('user-info');
testbut = document.getElementById('test');
var rr = getResponse("user_profile.xml");
if(rr != null)
{
response = rr;
}
if (response.authResponse) {alert('me/permissions/?access_token='+
response.authResponse.accessToken);
FB.api('me/permissions/?access_token='+ response.authResponse.accessToken
,function(response)
{
for (var name in response) {
alert(response.data);
}
alert(response);
});
//user is connected
FB.api('/me', function(info) {
login(response, info);
});
button.onclick = function() {
FB.logout(function(response) {
logout(response);
});
};
} else {
//user is not connected
button.innerHTML = 'Login';
button.onclick = function() {
FB.login(function(response) {
if (response.authResponse) {
FB.api('/me', function(info) {
login(response, info);
});
} else {
//user cancelled login or did not grant authorization
showLoader(false);
}
},
{scope:'email,user_birthday,status_update,publish_stream,user_about_me'});
}
}
}
// run for the current status and whenerve it is changed
FB.getLoginStatus(updateButton);
FB.Event.subscribe('auth.statusChange', updateButton);
};
(function() {
var e = document.createElement('script'); e.async = true;
e.src = document.location.protocol
+ '//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appendChild(e);
}());
function login(response, info){
if (response.authResponse) {
ajaxFunction(response);
var accessToken = response.authResponse.accessToken;
userInfo.innerHTML = '<img src="https://graph.facebook.com/' + info.id
+ "<br /> Your Access Token: " + accessToken;
button.innerHTML = 'Logout';
document.getElementById('other').style.display = "block";
}
}
function logout(response){
userInfo.innerHTML = "";
document.getElementById('debug').innerHTML = "";
document.getElementById('other').style.display = "none";
}
You have to store User access token in your database to user for next time.
Here is some small hint to pass access token using javascript sdk
FB.api('me/permissions/?access_token=Your access token',function(response){console.log(response)});
Chiming in a bit late, but my guess is you are trying to login using an expired or invalidated short-term access token. For future logins, you should convert the short-term access token to a long-term access token, good for about 60 days. The conversion to a long-term token needs to happen on your server as it requires your app-secret. Details are here. The long-term token is what you should be storing in your database (or similar) for future use.
I have a javascript function that uses fb.login to retrieve the users info and checks to see if the user likes my fb page. fb.login causes a pop up where the user must click a login button. If the user likes my page i need to first create a cookie then redirect them to the main app:
function checkUser() {
var page_id = "my id goes here"; //
FB.login(function (response) {
if (response.authResponse) {
console.log('Welcome! Fetching your information.... ');
FB.api('/me', function (response) {
var fql_query = "SELECT uid FROM page_fan WHERE page_id = " + page_id + "and uid=" + response.id;
var the_query = FB.Data.query(fql_query);
the_query.wait(function (rows) {
if (rows.length == 1 && rows[0].uid == response.id) {
//$("#container_like").show();/
//set cookie
document.cookie = "fbId=" + response.id;
window.location = "/kisses.aspx";
} else {
$("#likepageholder").show();
//$("#container_notlike").show();
//window.location = "/kisses.aspx";
//and here you could get the content for a non liker in ajax...
}
});
});
} else {
console.log('User cancelled login or did not fully authorize.');
}
});
}
If there a way around using fb.login to do this?
Nope. Unfortunately, you need the user to log in (and grant your app basic permissions [based on the appId you use in FB.init) in order to query the user's likes.
That being said, it looks like your code should work.