Search code examples
ruby-on-rails-3devise

Devise sign_out_and_redirect flash notice


I'm running a Rails 3.2.14 app with Devise 2.1.2 and am checking for concurrent/duplicate sessions in my application controller.

I'd like to be able to display a flash notice in template view after I call signout_and_redirect in my application controller that displays "Duplicate login detected"

Here's what my code looks like:

application_controller.rb

def check_concurrent_session
    if duplicate_session?
      flash[:notice] = "Duplicate Login Detected"
      sign_out_and_redirect(current_user)
    end
  end

  def duplicate_session?
    user_signed_in? && (current_user.login_token != session[:token])
  end

I've tried it with the above code, but when I trigger a duplicate session the browser does sign out but does not display the flash notice.

In my application.html.erb I have the following setup to display flash notice/alerts.

<% if flash[:notice] %>
  <p class="alert"><%= flash[:notice] %></p>
<% end %>
<% if flash[:alert] %>
  <p class="alert"><%= flash[:alert] %></p>
<% end %>

Solution

  • Could you use session?

    def check_concurrent_session
      if duplicate_session?
        sign_out_and_redirect(current_user)
        session[:duplication_notice] = "Duplicate Login Detected"
      end
    end
    
    # users/sessions_controller.rb
    
    def new
      if session[:duplication_notice].present?
        flash.now[:alert] = session[:duplication_notice]
        session.delete(:duplication_notice)
      end
      super
    end
    

    Lifetime of flash is until next action.

    1. sign_out_and_redirect
    2. authenticate_user!
    3. sign_in

    log

    Started GET "/" for 127.0.0.1 at 2015-04-13 17:08:02 +0900
    Processing by Users::FunctionsController#home as HTML
    Filter chain halted as :check_concurrent_session rendered or redirected
    Completed 302 Found in 9ms (ActiveRecord: 0.9ms)
    
    Started GET "/" for 127.0.0.1 at 2015-04-13 17:08:02 +0900
    Processing by Users::FunctionsController#home as HTML
    Completed 401 Unauthorized in 1ms
    
    Started GET "/users/sign_in" for 127.0.0.1 at 2015-04-13 17:08:02 +0900
    Processing by Users::SessionsController#new as HTML
    Completed 200 OK in 3258ms (Views: 3254.7ms | ActiveRecord: 0.3ms)
    

    Because sign_out clear the session, session set after sign_out.

    Anything you place in the flash will be exposed to the very next action