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 = './';
});
}
Related
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;
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.
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'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";
}
});
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).