Cakephp Ajax Login is loggin in even with wrong data - javascript

I have a simple html form to login outside my cake structure, I send the login data via jquery to my login function:
public function login() {
if ($this->request->is('ajax')) {
$this->request->data['Appuser']['password'] = Security::hash($this->request->data['password']);
$this->request->data['Appuser']['name'] = $this->request->data['name'];
if ($this->Auth->login()) {
return $this->redirect($this->Auth->redirectUrl(array('action' => 'returnUserData')));
}else{
$this->response->body(json_encode('Login failed!'));
}
}elseif($this->request->is('post')){
if ($this->Auth->login()) {
return $this->redirect($this->Auth->redirectUrl());
}else{
$this->Session->setFlash(__('Invalid username or password, try again'));
}
}
}
The very strange thing is:
the login via post from /view/users/login.ctp form works perfectly!
When I try to login from "outside" via ajax, I am always logged in even with wrong access details and get the data from function 'returnUserData'
$('#login').click(function() {
$.ajax({
type: "POST",
url: '/api/login',
data: {
name: $("#username").val(),
password: $("#password").val()
},
success: function(data)
{
alert(data);
}
});
});
When I set a debug(); after if ($this->request->is('ajax')) I can see it, so the script seems to go into the right if section. But I don't get it, why the $this->Auth->login always return true...?

Related

Asp .Net Core 2.2 Razor Pages Ajax Call Post not working

I've done so many ajax in razor pages but i can't figure out why this does not work. It keeps giving me error 400 on dev tools. It does not reach the page handler no matter what.
<script>
$.ajax({
url: "/Account/Users/Index?handler=Delete",
type: "POST",
data: {
id: id
},
success: function () {
swal("Utilizador Desactivado!", {
icon: "success",
});
},
error: function (xhr, ajaxOptions, thrownError) {
swal("Falha na ligação ao servidor. Tente novamente mais tarde.");
}
});
</script>
page handler
public async Task<IActionResult> OnPostDeleteAsync(int? id)
{
if (id == null)
{
return NotFound();
}
var user = await _context.Users.FindAsync(id);
if (user != null)
{
user.IsActivo = false;
_context.Users.Attach(user).Property( u => u.IsActivo).IsModified = true;
await _context.SaveChangesAsync();
}
return RedirectToPage("./Index");
}
I tried many url combinations and none work. I don't see what is wrong in here....
EDIT
It seems like the problem is the anti forgery token not being validated on razor page.
I wrote Ignore Anti forgery Token on the page model and everything works correctly
As you've already found out it's the anti forgery token, that is ruining your day.
Now, if you are inside a form, asp.net core will create a hidden input with that token for you. If you are not working with a form on your page, you'll have to call #Html.AntiForgeryToken(), which will add the token for you.
Still, this will not resolve the Bad Request for you. You have to add it to your ajax call:
$.ajax({
url: "/Account/Users/Index?handler=Delete",
type: "POST",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN", $('input:hidden[name="__RequestVerificationToken"]').val());
},
data: {
id: id
},
});
Additionally, add this line to your Startup.cs file:
services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN");
I don't know what you mapping of URL use, but as usual it consists of controllerName/actionName/. In your case try to use:
url: "/Account/OnPostDeleteAsync"
or
url: "/Users/OnPostDeleteAsync"
but if your URL is correct, then try to use [FromForm] attribute
public async Task<IActionResult> OnPostDeleteAsync([FromForm]int? id)
I hope this will help

Ajax does not want to send me a PUT query

I want to send to the controller a new e-mail given by the user using ajax
$.ajax({
type: 'PUT',
url: '/changeEmail?',
data: {
email: function() {
return $('#email').val();
}
},
success: function(result) {
console.log('function');
if(result === true) {
console.log("true");
} else {
console.log("false");
}
}
});
To the controller (sample code)
#PutMapping("/changeEmail")
public boolean changeEmail(
#RequestParam("email") String email
) {
System.out.println("email: " + email);
return true;
}
However, when dispatching, the browser console throws me out
jquery-3.2.1.min.js:4 PUT http://localhost:8080/signIn net::ERR_TOO_MANY_REDIRECTS
Ajax is trying to send data to a completely different address than the one I provided in ajax.
In Ajax I gave
/changeEmail
And he is trying to send me on
/signIn
What this is about?
A couple of issues here. Firstly remove the ? from the end of the URL. jQuery will add it automatically, if required.
Secondly don't provide a function in the object you set to data. Give the value directly. Also, result will be a string, so your comparison to a boolean will not work as you expect. To be safe while testing, it's best to just log the response directly. Try this:
$.ajax({
type: 'PUT',
url: '/changeEmail?',
data: {
email: $('#email').val();
},
success: function(result) {
console.log(result);
}
});
Lastly, if your request is being redirected from /changeEmail to /signIn, then it sounds like you will need to authenticate the request. Exactly how you do that varies from one API to another, so I'd suggest you check their documentation.

How to wisely redirect after successful ajax login?

I have a method calling ajax and after success I need to redirect to another page.
I think when ajax call ends my URL is by default changed, ending with my username and password which I have posted in the ajax call.
How to wisely handle this? I am not in a situation to remove async false and I know I can send password and username using ajax given keys.
function Login() {
var model = { user_Name: $("#username").val(), Password: $("#password").val() };
$.ajax({
async: false,
url: 'http://localhost:51525/api/HomeApi/',
type: 'POST',
data: JSON.stringify(model),
dataType: "json",
success: function (data) {
alert("Function is successfully returned now redirect");
//how to redirect??
//window.location.href = 'http://localhost:51525/user/';
//window.location.href = '#Url.Action("Index","User")';
}
});
}
The reason that your url shows the username and password is because you are triggering the form submit with the default method="GET".
There are lots of alternatives. E.G.:
Return false from your Login. This will disable the form submit.
function Login() {
//Your code...
return false;
}
Or
Don't use ajax at all, and use a normal form post:
<form method="POST" action="/api/HomeApi/">
Additionally, there are other ways a user might submit the form so <form onsubmit="Login()"> is probably better than <input onclick="Login()">

not going through the django view through ajax post data

I am doing the login throgh ajax. jquery function is working fine but its not going to the ajax url. So django view is not getting executed.
Ajax.html
$(function()
{
localStorage['domain'] = "http://122.172.64.142";
var domain = localStorage['domain'];
$('#fac1').on('click', function () {
var username = $("#username").val();
var password = $("#pwd").val();
data = {
name: username,
password: password
};
alert(domain);
$.ajax({
url: domain + "/login/login_android_here/",
type: "POST",
data: data,
success: function (response) {
alert("success");
window.location = 'file:///android_asset/www/posts.html';
},
error: function () {
alert('some error in login');
}
});
return false;
});
});
My django views.py
#csrf_exempt
def login_android(request):
print "i am in view"
if request.method == "POST":
print "you are in method"
username = request.POST['name']
password = request.POST['password']
login_api(request,username,password)
#return HttpResponseRedirect('/home/')
messages.success(request, 'You Loged In Successfully')
response = json.dumps(username)
return HttpResponse(response, mimetype="application/json")
When i click on login button i am getting alert but its not getting entered to view. Url is correct.
I would first recommend using Chrome with the developer tools console open.
You could change you alerts for console.log().
When your trying window.location = 'file:///android_asset/www/posts.html';
You are trying to access a local resource. If I post that in my Chrome developer tools I get back
Not allowed to load local resource: file:///android_asset/www/posts.html
If you would use window.location.replace("a url to your view"); this will work like a HTTP redirect.
for more information redirect page
and you should be able to see your view.
I was made a silly mistake. I provided a wrong domain address on this page. Now it worked.
localStorage['domain'] = "http://122.172.64.142";
This address was wrong. Thats why it was not able to enter in to the view.
You forgot dataType ajax param
$.ajax({
url: domain + "/login/login_android_here/",
type: "POST",
data: data,
dataType : 'json', //dataType param IS MISSING
success: function (response) {
alert("success");
window.location = 'file:///android_asset/www/posts.html';
},
error: function () {
alert('some error in login');
}
});

JQuery $.ajax 302 redirecting on the first call only

I've written a function to call a local API using POST:
function setOpenGraph(setValue) {
requestData = {
user : $.user._id,
opengraph : setValue
};
console.log(requestData);
$.ajax({
type: 'POST',
data: requestData,
dataType : 'json',
url: '/api:setopengraph',
success: function (data) {
$.user.opengraph = setValue;
console.log(data);
}
});
}
This works when called on a click event for a link on the page. However when I call it as a response to an alertify popup is fails to POST the data to the api:
alertify.set({ labels: { ok: "ON", cancel: "OFF" } });
alertify.confirm( 'message here', function (e) {
if (e) {
$(".toggleopengraph").html('turn facebook sharing off');
setOpenGraph(true);
} else {
$(".toggleopengraph").html('turn facebook sharing on');
setOpenGraph(false);
}
});
**In both cases console.log() returns Object {user: "XXXXXXXXXXXXXX", opengraph: false} **
Bellow you can see the console output where the first request (Initiated by alertify) is redirected and does not POST to the API. The second (Initiated by .click()) POSTS the data to the API.
Somehow calling the function first outside alertify cleared this error... strange.

Categories

Resources