简体   繁体   中英

How to check if a user is authenticated with Devise on an AJAX call in rails?

I have a button that allows a person to join a group (called a pod in my application). The button uses remote: true to do an AJAX call. I have a join table that manages the relationships between users and pods with has_many: though:. In the join table controller I want to be able to check if the user is authenticated before that user can join a pod. If not authenticated, the user should be taken to a log in page and then back to the page with all the pods listed.

Right now, I've got the following code in pod_users_controller:

  before_action :user_logged_in

  ...

  private

  def user_logged_in
      render :js => "window.location = '#{new_user_session_path}'" unless user_signed_in?
  end

In my application controller I have the following code to redirect the user back to the page they were on before authenticating:

  def store_location
     session[:previous_url] = request.fullpath unless request.fullpath =~ /\/users/ 
  end

  def after_sign_in_path_for(resource)
      session[:previous_url] || root_path
  end

It's kind of works but it feels very flaky. For example, I have another button which allows you to create a new group with an AJAX bootstrap modal. I've tried using the same method with before_action :user_logged_in in the pods_controller file. It pops the modal without the form and then redirects. Or when I click on the join button it will redirect me to the form to create a new pod if I just clicked the "start a pod" button before that.

My question is, is there a better way to do what I'm doing? How do I redirect to login before the modal pops? I'm just learning ruby and rails so any best practices would be much appreciated. Also, this is a total side question but in this approach I have the same method I'm calling "user_logged_in" from two controllers. Right now I have that method at the bottom of both. I'm assuming there's a place I can put it to make it accessible by multiple controllers from one place?

Thank you!

I'm on Rails 4.2 and Devise 3.4

Devise comes with these helpers: https://github.com/plataformatec/devise#controller-filters-and-helpers

That includes the before_action :authenticate_user! as well as the user_signed_in? helper (almost the same name as yours), which is available throughout the app. You could use user_signed_in? to redirect from within a view with ERB or in a controller.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM