Viren
Viren

Reputation: 5962

Devise Session destroy with ajax request how should I approach

I have a form where user can fill in the details the form field contain an email_id column

Now if the user is logged in there would appear a link stating

"NOT USER NAME" e.g "NOT VIREN NEGI" against that email field which would be a ajax request.to destroy the devise session

Once user click the link the devise session would be destroyed and on success of ajax the above anchor tag would be disapper

I have implemented this solution by Moneypatching the destroy method of Devise like

class DeviseSessionsController < DeviseController

  def destroy
    .... DEVISE CODE ...
    .... DEVISE CODE ...
    .... DEVISE CODE ...

     respond_to do |format|
       if request.xhr? **## My Hack**
         format.js { render :partial => 'users/signout' } **## render signout partial on ajax request** 
       else 
         format.any(*navigational_formats) { redirect_to redirect_path }
        format.all do
          method = "to_#{request_format}"
          text = {}.respond_to?(method) ? {}.send(method) : ""
          render :text => text, :status => :ok
       end
     end 
    end
  end
end

This all though seem to work but since but I'm not happy with this

  1. does not suit if devise updated and in future destroy method might look different what it is currently
  2. I have copy all the other action method of devise/sessions_controller to have devise working without any problem

Can anyone Help me on this

Please Avoid answering that monkeypatching is bad asking me to read about monkeypatching all those stuff (I know that) that why the question is posted.

Thank You

Upvotes: 0

Views: 1612

Answers (2)

Viren
Viren

Reputation: 5962

you can use devise helper method signout

create a action inside users controller

def log_me_out 
   signed_out = (Devise.sign_out_all_scopes ? sign_out : sign_out(resource_name))
    respond_to do |format|
      format.js  { render :partial => 'log_me_out',:layout => false }
    end
end

This will save you from moneypatching devise#sessions controller

Hope this help

Upvotes: 2

Jakub Oboza
Jakub Oboza

Reputation: 5421

You need to add csrf meta tag to request. I think this is the problem, not in devise.

this should solve it

$.ajaxSetup({
  'beforeSend': function(xhr) { xhr.setRequestHeader('X-CSRF-Token', $("meta[name='csrf-      token']").attr('content')); }
});

Upvotes: 0

Related Questions