I have a problem using devise with an AJAX login. I'm using the :remote => true
option and the jQuery version of the javascript helpers (https://github.com/rails/jquery-ujs).
Ehen the user enters the correct informations, my create.js.erb inside the sessions view is rendered. This is ok, 'cause i can redirect my user using JS in this file. But when an error occurs, e.g. the user enters false information, only the flash messages are in the response with an error code 401 - Unauthorized
. So, no view or create.js.erb or sth else is rendered.
But I want to handle this message, by displaying it on the side, so that the users gets some feedback, whats wrong.
I also tried to implement my own custom controller with respond_to :js
, and playing with the :recall
method of the warden authentication. But it doesn't work.
Does anybody know some best practices to solve this problem? Or should I avoid this helper methods and just use pure jQuery for the ajax calls?
thx, tux
Devise is an excellent authentication system made for Rails that allows us to easily drop-in User functionality into our project. Devise only includes an email and password for registration, let's also add our own username to our User model. We also want to have a unique index on our username.
The devise gem is basically based on a warden gem, which gives an opportunity to build authorization direct on a Ruby Rack Stack. This gem is pretty straightforward and well documented. Warden fetches a request data and checks if the request includes valid credentials, according to a defined strategy.
You could use the jQuery event "ajax:error" in rails 3. Just bind the event to your form.
jQuery(function($) {
$("#new_model").bind("ajax:error", function(event, data, status, xhr) {
alert("something went wrong");
});
});
Take a look at this blog post for more details on what events are available.
Here's my version
<script>
$(document).ajaxError(function(e, XHR, options){
if (XHR.status == 401){
window.location.replace("<%= new_user_session_path %>");
}
});
</script>
It automatically redirects the user to the login page and works for all elements on the page.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With