Search code examples
ruby-on-railsruby-on-rails-4devisewarden

Redirect to log in page if user is not authenticated with Devise


I'm using Devise with Ruby on Rails.

What is the recommended way to redirect unauthenticated users to the sessions#new page if they attempt to access a page that requires authentication?

Right now I get an error that says no route matches the one they attempt to access (leading to a 404 error in production).


Solution

  • Just simple add this method to application_controller.rb

      protected
      def authenticate_user!
        if user_signed_in?
          super
        else
          redirect_to login_path, :notice => 'if you want to add a notice'
          ## if you want render 404 page
          ## render :file => File.join(Rails.root, 'public/404'), :formats => [:html], :status => 404, :layout => false
        end
      end
    

    And you can call this method on before_filter another controllers you want.

    e.g :

    class HomesController < ApplicationController
      before_filter :authenticate_user!
      ## if you want spesific action for require authentication
      ## before_filter :authenticate_user!, :only => [:action1, :action2]
    end
    

    Don't forget add login_path into routes.rb

    devise_scope :user do
      match '/sign-in' => "devise/sessions#new", :as => :login
    end
    

    note : I always use this way when play with devise for my apps authentication.. (rails 3.2 and rails 4.0.1)