Avoid manual Ajax calls when authorizing with Facebook JavaScript SDK - javascript

I'm going to use Facebook JS SDK to login users to my site.
function myLogin(){
FB.api('/me',{fields: 'name,email'}, function(response) {
if(response.email){
//Ajax call function
jQuery.ajax({
url: 'inc/social_logins/fb/account_auth.php',
type: "POST",
data: { func: 'nac', name: response.name, email: response.email},
success:function(data) {
if(data == 1){
window.location = "user_dashboard.php";
}
}
});
//Ajax call function ends
}
}
Above ajax request calls account_auth.php and it checks for accounts associated with the email comes with FB authorization. And if FB authorization returns true, it runs the myLogin() in the following logic.
function statusChangeCallback(response) {
if (response.status === 'connected') {
qksellLogin();
}
}
Everything works fine and gets redirected to the private dashboard area after FB login popup window closed.
What I want to do is, to block manual Ajax requests by unauthorized users.
Let's say if I can fake the response object and add someone else's FB name and email, then I call the above Ajax call function in the console, it still runs and logs in. That's terrible huh...
So, what actions may I want to take here ?

Related

Can't login after logout Laravel

I have developed a dynamic page with javascript (no reloading) where a user inserts a private number.Then I send a Ajax request to manually log in the user associated with that number.After that if the user wants he can exit (send Ajax request to logout) and the main page appears to log in again.
Steps To Reproduce:
Enter Number, click login and I verify that the first login works.
Click exit and the logout works
Insert same or another number and click login again and now the user is not authenticated.
Note: If I refresh the page after exit(logging out), the 2nd login works.
-> Code where I send Ajax request to verifyNIF()
$('#start').on('click', function() {
$.ajax({
url: '/' + slug + '/vote-in-person/verify-nif',
type: "POST",
data: {
nif: nif
},
dataType: "json",
success: function (data) {
//NIF VERIFIED AND USER LOGGED IN
}
});
});
-> verifyNIF() verifies the number on the DB and then authenticates the user
Auth::login($user);
-> logout() function, which uses Laravel Fortify logout route.
function logout(){
$.ajax({
url: '/logout',
type: "POST",
success: function () {
console.log("logged out");
// location.reload();
},
error: function (data) {
console.log(data);
}
})
}
On the front side, the CSRF token becomes invalid after logout with an ajax request. You can add a new endpoint to refresh the CSRF token manually. I think that helps you. https://stackoverflow.com/a/57252273/9215587

How to create secure page for a mobile app using phonegap

I'm working a simple mobile app and I'm using HTML, CSS, Javascript, ajax, PHP and Mysql and Phonegap. The mobile app has a login and I'm using ajax to send the data to a php file located on a separate server if the login is successful the app loads a diferent page, only users that are register can see this page.
The problem that I'm facing is that when I'm on the next page I don't know how to verify that the user has the access. I was thinking on using a window variable or localstore but I don't know if this is a good idea or not.
Can some one point me in the right direction on this topic.
Just sit and think. Use localStorage.setItem if user is registered/logged on ajax call. Later control that on easy way. Check this example.
Ajax call:
$.ajax({
type: "POST",
url: "http://exampleUrl.com/php1/insert.php",
data: dataString,
crossDomain: true,
cache: false,
beforeSend: function() {
$("#insert").val('Connecting...');
},
success: function(data) {
if (data == "success") {
alert("You can login now!");
$("#insert").val('Wait...');
localStorage.setItem("logged", logged); // Save if user is successfuly registered and control on other page
//console.log(dataString);
loadiranje_paIndex();
} else if (data == "error") {
alert("Error! Try another username!");
$("#insert").val('Register');
/*location.href = '/register.html'; */
}
}
});

How to redirect a user to a login page from a servlet? [duplicate]

This question already has answers here:
How should I use servlets and Ajax?
(7 answers)
Closed 5 years ago.
I am trying to redirect a user to the login page of the website from page A if at the time of the page load no login details are found in the session. I am using a servlet for the same.
From page A, I am making the most basic AJAX call at page load to my servlet as below:
$.ajax({
url: "/bin/website/protectedpage.html",
success: function(){
}
});
However, I have only been able to achieve the following results with the mentioned approaches:
1.
response.sendRedirect("/content/website/en/login.html");
resulting into an HTTP code 302 in response but no redirection actually happening. Also, there is nothing returned in the response body.
2.
ServletContext context= getServletContext();
RequestDispatcher rd= context.getRequestDispatcher("content/website/en/login.html");
rd.forward(request, response);
resulting into a Response code 200 returning the whole login page HTML in the response body but still not redirecting the user to the login page.
What am I missing? Please help me with the same. Thanks in advance.
$.ajax() performs an asynchrounous HTTP call to the server. Redirecting the call just from the server won't also redirect on the browser. You will have to handle the redirection after the ajax call on the front-end itself.
You can try something like this
$.ajax({
type: "POST",
url: URL,
data: reqBody,
dataType: "json",
success: function(data, textStatus) {
if (data.redirect) {
// Redirect here
window.location.href = data.redirect;
}
else {
// No redirection.
}
}
});
PS: Code block copied from here.
you can use window.location.replace("url") (simulate an HTTP redirect).
If ypu prefer, you can use window.location.href = "url". This is similar to click a link.
The function replace() does not keep the originating page in the session history, so the user can't get stuck in a never-ending back-button. For me, replace() is the best choice.
Would you have tried something like
function_name(funct) { return function(data) { if($("#myForm", data).size() > 0) top.location.href="login"; else funct(data); } }
for example
function sample(data, funct){
if($("#myForm", data).length > 0)
top.location.href="login.htm";//redirection
else
funct(data);
}
Then, when making the Ajax call we used something like:
$.post("myAjaxHandler",
{
param1: sam,
param2: kari
},
function(data){
sample(data, myActualCB);
},
"html"
);
all Ajax calls always returned HTML inside a DIV element that we use to replace a piece of the page. Also, we only needed to redirect to the login page.
We basically have an ISA server in between which listens to all requests and responds with a 302 and a location header to our login page.
Now check for status 302 as you have mentioned above that you are getting response 302
$(document).ajaxComplete(function(e, xhr, settings){
if(xhr.status === 302){
var loginPageRedirectHeader = xhr.getResponseHeader("LoginPage");
if(loginPageRedirectHeader && loginPageRedirectHeader !== ""){
window.location.replace(loginPageRedirectHeader); //check for location header and redirect...
}
});

Login Form API Response Code

I'm creating an API endpoint for a mobile app and for computer web browsers. Both devices use the same API endpoint with a POST request sent to /users/session for authentication. The mobile phone requires a 200 Status Code response. However, as login forms do, I need to redirect browsers to the home logged in page where the user can see their information. Do I return a 301 subsequently after? What is the best practice to implement this?
In summary: I need to use the same API endpoint for mobile and computer, but am unsure how to redirect while returning a 200 Status Code.
It seems like a 200 OK is the proper code to return upon successful login. This makes the API more generic and doesn't tie it to any particular use (mobile vs desktop). You might try placing the redirect logic in the desktop site itself and use ajax to submit the data. This will give you more flexibility for handling login errors as well. This is a basic example with jquery.
$.ajax({
type: "POST",
url: "/users/session",
data: loginForm,
success: function(){
//Redirect user to home page
window.location.replace("/home");
},
dataType: dataType
});
try this
$.ajax(serverUrl, {
type: "POST",
data: dataToSave,
statusCode: {
200: function (response) {
alert('200');
},
201: function (response) {
alert('201');
}
}, success: function () {
alert('1');
},
});

Using window.location.replace after an Ajax response does not redirect immediately

I am implementing facebook connect for authentication. I also want to verify that the email of the user I receive from facebook matches with an internal database (essentially invite list). So I use an ajax call as below. However, the redirect does not happen immediately. The user needs to refresh the window in order to get redirected. Any ideas why and how this can be fixed? Thanks!
Note that this happens within FB.api which in turn is inside window.fbAsyncInit.
$.ajax({
type: "POST",
url: "verifyLogin.php",
data: ("email=" + myEmail),
success: function(resp){
if (resp == 'success')
{
window.location.replace('/index.php');
}
},
error: function(e){
alert('Error: ' + e);
}
});
This should be immediately after the request has returned success have you tested that the response occurs immediately if you are not inside the facebook window class?
also the resp check should not be necessary if you are not returning the word "success" from verifyLogin.php
Tell us more about what you mean about immediately.

Categories

Resources