FB.logout with server side code session cleanup - javascript

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

Related

login callback don't run with facebook account kit after success login?

hello i want to implement facebook account kit to login with sms on my localhost i follow the code as in the docs
<script>
// initialize Account Kit with CSRF protection
AccountKit_OnInteractive = function(){
AccountKit.init(
{
appId:"{{FACEBOOK_APP_ID}}",
state:"{{csrf}}",
version:"{{ACCOUNT_KIT_API_VERSION}}",
fbAppEventsEnabled:true,
redirect:"{{REDIRECT_URL}}"
}
);
};
// login callback
function loginCallback(response) {
if (response.status === "PARTIALLY_AUTHENTICATED") {
var code = response.code;
var csrf = response.state;
// Send code to server to exchange for access token
}
else if (response.status === "NOT_AUTHENTICATED") {
// handle authentication failure
}
else if (response.status === "BAD_PARAMS") {
// handle bad parameters
}
}
// phone form submission handler
function smsLogin() {
var countryCode = document.getElementById("country_code").value;
var phoneNumber = document.getElementById("phone_number").value;
AccountKit.login(
'PHONE',
{countryCode: countryCode, phoneNumber: phoneNumber}, // will use default values if not specified
loginCallback
);
}
// email form submission handler
function emailLogin() {
var emailAddress = document.getElementById("email").value;
AccountKit.login(
'EMAIL',
{emailAddress: emailAddress},
loginCallback
);
}
</script>
everything work as charm i enter phone and i receive sms then i verify the code and now is the problem after the code verify the login call back should be excuted so i can connect with the server but this method never execute, why?
notes: my app in development
i enabled debug true but there is no problem shown on console
i try many thing but nothing worked the login callback never run
so how i can make the login call back executed so i can connect with server?
You need to use some ajax mechanism after this line:
var csrf = response.state;

Restrict user from visiting a page without logging in using javascript

I have made a register form, from where data is getting stored into the local storage. Only after user logs in successfully, it redirects to success.html or else takes user back to the login page. I have added the following script at the head of success.html-
<script>
if (localStorage.getItem('status') != null)
{
//redirect to page
window.location.href = "success.html";
}
else
{
//show validation message
window.location.href = "login.html"
}
</script>
and following is my login validation function-
//Storing data from local storage into an array of objects
var usersdata = JSON.parse( localStorage.getItem('key_users' ) );
function loginvalidate()
{
usersdata = JSON.parse( localStorage.getItem('key_users' ) );
var usernameinput = document.getElementById("username");
var passwordinput = document.getElementById("password");
for(var p in usersdata)
{
console.log(p+':'+usersdata[p].username+'|'+usersdata[p].email);
if(usernameinput==usersdata[p].username && passwordinput==usersdata[p].password)
{
alert("Logged in successfully");
}
}
jQuery(window).load(function() {
localStorage.setItem('status','loggedIn')
});
}
Here, I am unable to set the status to 'loggedIn' and if I set it manually through console the success.html keeps on loading just like running any infinite loop.
The loop is occurring because of the following condition on the success page. It redirects even when you are at the success page and thus the loop.
if (localStorage.getItem('status') != null)
{
//redirect to page
window.location.href = "success.html";
}
Change it to
if (localStorage.getItem('status') == null)
{
//show validation message
window.location.href = "login.html"
}
P.S. I do highly recommend not to use localstorage to send the username and password to the clientside. It breaks the whole point of authentication and authorization services even existing.

Promise to execute a particular code first

I have the following scenario. Actual Page loading starts, user login is checked for authentication. If access granted, actual page loading completes and user can access the page. If access denied, actual page loading stops and user is redirected to 'access denied' page.
Infact the scenario should be like this. User authentication is checked. if access granted, actual page loading starts and user can access page. If access denied, user is directly directed to 'access denied' page.
can someone tell me how to include promise for this scenario. current code is as follows.
$q.when().then(function () {
return $rootScope.$emit('resetView', false, 'default');
}).then(function (result) {
loadNavBar(); //actual page loading starts here
}, function (error) {
$log.error("Caught an error:", error);
return $q.reject('New error');
});
the below function is loadNavBar() which gets executed. User authentication is done inside of this. Hence page loading starts and then user is checked. I want user to be checked first itself and then load page accordingly depending on his access rights.
var loadNavBar = function () {
//few functions here to display page.
//below code to check user authentication
var serviceURL_CheckUserExists = '/api/Pre/CheckUserExists';
//ajax to check if user exists in database. give/ deny access based on user present in DB and if user is set as blockuser in db.
$.ajax({
type: "GET",
url: serviceURL_CheckUserExists,
}).then(function (response) {
if (response.Results.length == 1 && response.Results[0].BlockUser == false) { //user has access if condition is satisfied.
$rootScope.myLayout.eventHub.emit('getUserName', response.Results[0].User_ID.trim());
$scope.role = "";
var details = response.Results[0];
for (var parameters in details) {
if (details[parameters] == true) {
$scope.role += parameters + ',';
}
}
$scope.role = $scope.role.replace(/.$/, ".");
var firstname = response.Results[0].FirstName;
firstname = firstname.replace(/\s/g, '');
$scope.$apply(function () {
$scope.username = response.Results[0].FirstName + " " + response.Results[0].LastName;
});
}
else { $window.location.href = '../../../BlockUser.html'; } //block access to actual page and redirect to 'access denied' page.
}
}
});
};
i think that the right approach to your problem is to use resolve property in the route, so the user can't navigate to certain pages if he isn't logged in and once he logged in you can inject the user object to the controller
for example to navigate to home page you must be logged in
.when("/home", {
templateUrl: "homeView.html",
controller: "homeController",
resolve: {
user: function(AuthenticationService){
return AuthenticationService.getUser();
}
}
})
app.controller("homeController", function ($scope, user) {
$scope.user = user;
});
https://www.sitepoint.com/implementing-authentication-angular-applications/
Here's a quick example of hiding the content until the user is authenticated to see it. Click the 'authenticate' button to trigger the function that you would run if the user is authenticated by your ajax call. Showing the content can be done with a fuction like:
function userIsAuthenticated(){
document.getElementById('pageContent').style.display = 'block';
}
See JsFiddle for a simple implementation.

facebook javascript sdk - how to check if user likes page without fb.login pop up

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.

Chrome Extension: popup.html closes and opens response in a new tab?

I've got a login form on my popup.html which calls the following function...
chrome.extension.sendRequest({
req: "login",
user: username,
pass: pass,
remember: remember
}, function(response) {
console.log("RESPONSE RECIEVED HOOORAH!");
});
this function in turn goes to the following switch statement in my background.html..
do_login(request.user, request.pass, request.remember, false, true, function(response){
if(response == true){
sendResponse("success");
}else{
sendResponse("badLogin");
}
})
the following is the contents of do_login. During the execution of do login my popup.html randomly closes and reopens in a new tab, the code is completed there and I'm logged in. Why is this happening?
var xhr = new XMLHttpRequest();
xhr.open("GET",requrl,true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
xhr.onreadystatechange = function(do_login){
if(xhr.readyState == 4){
if(xhr.status == 200){
console.log(xhr.responseText);
try{
//Incase they were just logged in as another user.
createContextMenu();
//users info.
var resp = JSON.parse(xhr.responseText);
if(resp.default === void(0)){
logOut();
callback(null);
}
default = resp.default;
for(var i=0;i<resp.s.length;i++){
globalStaks[i] = resp.s[i];
}
st = global;
bud = resp.bud;
msg = resp.msg;
stakid = resp.default;
}catch(x){
// This situation is where you have incorrect password
console.log("something is wrong with logging in ")
clearLoginInfo();
console.log("Incorrect password");
}
if(resp.msg == "denied")
{
clearLoginInfo();
callback(false);
}
else
{
loggedIn = true;
user = username;
userid = resp.userid;
if(refresh){
refreshpage();
}
if(notificationdisplay){
notification.cancel();
}
if(remember)
{
clearLoginInfo();
storeLogin(username,pass);
}
localStorage.setItem("pass",pass);
md5 = pass;
callback(true);
}
}else {
callback(false);
}
}
}
xhr.send(null);
EDIT
It appears as the last error recieved background.html throws.. Attempting to use a disconnected port object
full trace is...
Uncaught Error: Attempting to use a disconnected port object
chrome.Port.postMessagechrome/RendererExtensionBindings:147
chromeHidden.Port.dispatchOnConnect.connectEventchrome/RendererExtensionBindings:89
sendResponse.reply background.html:1266
xhr.onreadystatechange
The code and data in a popup is ephemeral, in that as soon as the popup closes the associated code closes with it, therefore any callback from say a background page to the popup will fail (there is nothing to call back to).
You need to find what is opening the new page (not all your code is included in the question - what does createContentMenu do?). Desktop Notifications can cause you to lose focus and thus potentially close the popup.
Also make sure you catch the form submit in your popup and then pass the request through XMLHttpRequest (or use an embedded imframe to host the form), as form submission in a popup doesn't work as you might think (you page will not update inside the popup).

Categories

Resources