Problem is when user finished his work don't log out and leaves open page which requires authentication.
Next day he comes obviously session is lost and he is logged out, but he don't realize that and uses his open window where ajax functionality is.
How can I get right response to alert him to logout or redirect to login page, because I can't access method in where I could return response that user is logged out.
For example in Codeigniter I can still access my route check if user is logged in and return right response but I don't know how to do this in Laravel in the right way.
I am using ajax to save settings like this:
$.ajax({
type: "POST",
url: "{{ route('save.settings') }}",
dataType: "json",
data: { "data" : postData, "_token": "{{ csrf_token() }}"},
success:function(data_response){
console.log(data_response); // user is logged out
if(data.respone.user_logged){
//continue
}else{
window.location = '/login'; // force to login window
}
}
});
Related
I am working with CakePHP 3.6. I have a function that will return some data using AJAX call. This function will be called from any page of my website. It is like a button will be there and on clicking that button a modal will come with some data. Those data will come from AJAX call. So now the problem I am facing is with Csrf token. If I click from a page where a form is available then this AJAX call working perfect because there is a Csrf token available because of that form. But when I try clicking from a page where no form is available then AJAX is giving Csrf error. Because there is no Csrf added for that page.
This is how my button click and Ajax calling function looks like
$("#td-apt").on('click', function() {
getModalData();
$("#data-modal").modal('toggle');
});
function getModalData () {
$.ajax({
type: "POST",
url: "/function/Data",
headers: {
'X-CSRF-Token': $('input[name="_csrfToken"]').val()
},
dataType: "json",
success: function(data) {
console.log('success')
},
error: function() {
alert('Error');
}
});
}
So here are the things is it possible to generate Csrf token every time before calling this AJAX url. Or any other way to do this. Thanks
You can obtain the token from the request object in your view templates, for example in the layout to make it globally available:
<script>
var csrfToken = <?= json_encode($this->request->getParam('_csrfToken')) ?>;
// ...
</script>
You can then easily use it in your AJAX requests:
$.ajax({
headers: {
'X-CSRF-Token': csrfToken
},
// ...
});
Alternatively, if you already have some JS cookie parser at hand, you can obtain it from the cookie named csrfToken.
See also
Cookbook > Middleware > Cross Site Request Forgery (CSRF) Middleware
Cookbook > Middleware > CSRF Protection and AJAX Requests
I am having problem for ajax posts to my django ecommerce site after user login. The failing scenario is as follows:
1-) User comes to site and adds products to shopping cart without any problem. Adding product to cart is an ajax call and the code is as follows:
function addItemToCart(item_pk, quantity) {
var item_quantity;
if (!quantity) {
item_quantity = 1;
} else {
item_quantity = quantity;
}
$.ajaxSetup({
beforeSend: function(xhr) {
xhr.setRequestHeader('Csrf-Token', csrftoken);
}
});
$.ajax({
type: 'POST',
url: '/api/cart/add-item/',
data: {
item: item_pk,
quantity: item_quantity
}
success: function(data, textStatus, jQxhr) {
updateCart();
},
error: function(jqXhr, textStatus, errorThrown) {
console.log(jqXhr, textStatus, errorThrown);
}
});
}
The above code works perfectly and user can add several products to the cart.
2-) After that the user logs in to the site to make the payment, but before he make the payment he wanted to add another product to the cart, but the code fails.
3-) The error message is as follows: "CSRF Failed: CSRF token missing or incorrect."
When I checked the request I see that the ajax call already set the csrf token. The only thing I figured out is that django has refreshed the token after user login. But I also make sure that ajax call has been set csrf header with the new one.
So, I am confused why it works before user login and it does not work after user login. Because both posts has been made with the correct csrf tokens.
Any idea about what am i missing?
This is happening because Django uses csrf verification on POST requests, and your AJAX function is not properly passing csrf verification information. The Django docs have a good section on this that outlines some additional jQuery function you'll need to include to make a successful AJAX post using Django.
I have solved the problem:
The problem was the token header name. I was using the header name as 'Csrf-Token' and I still do not understand why it works for offline users but, it should be ''X-CSRFToken'. Maybe it is a bug for Django 2, I don't know.
I want to redirect user automatically to the login page when session expires.
I know by Auth::check() i can check if user session exist or not. but if user refresh the page then only it is redirecting to login.
Suppose user's session expires, then immediately i want to redirect to login page without waiting for user to refresh the page.
Is it possible. please tell me the right way to do it.
I thing is not possible to with out any click you need a click listener
as work with ajax like this
in env file so find line SESSION_LIFETIME=10 value change as wish in minate
and now
$.ajax({
type: "GET",
url: filename,
contentType: false,
success: function (data) {
// loaded your content without expire the sessions
},
error: function (xhr, status, error) {
// you redirect tht to login page
//hint: the laravel has unauthorized error for session expire or for Unauthorized users
if (error === 'Unauthorized'){
location.assign("login");
}
}
});
I have a website in localhost:8080, that has a window to log in to Facebook. When I make the request like this:
function fb() {
$.ajax
(
{
type: "POST",
url: "https://www.facebook.com",
data: {
username: $("input[name = 'username']").val(),
password: $("input[name = 'password']").val()
},
success: function(data, text, status) {
alert(status.status);
}
});
}
it keeps returning me 200 status even if I provide incorrect details. I suppose it just returns me the whole page...
How can I make this work? I want the Facebook page opened and logged in if credentials are correct and if credentials are wrong, I want error code to be returned.
You cannot use ajax to post to another domain or the server has to enable CORS for your domain. But you can use the FB login: https://developers.facebook.com/docs/facebook-login/web/login-button
I would like to give users the option to post tweets by entering only the url of the tweet (i.e. they would paste https://twitter.com/inspiredmag/status/342771390283411456 and then the actual tweet embed code, once received will be saved into the database to be displayed later). I'm not too familiar with the twitter api. i assume that once the user enters the url and clicks submit i will be able to get the embed code and then save it. is there a way I can grab it before submit and show a preview to the user?
Figured it out
<script>
$('#tweetLink').on('input', function() {
var url = $('#tweetLink').val();
if(url)
{
$.ajax({
url: "https://api.twitter.com/1/statuses/oembed.json?url="+url,
dataType: "jsonp",
async: false,
success: function(data){
$("#embedCode").val(data.html);
$("#preview").html(data.html)
}
});
}
})
</script>