Reputation: 25542
I am setting up a very simple rails app that involves a simple authentication check before you can enter the site. But, when the before_filter
runs, and the user is redirected to the login path, a redirect loop occurs.
ApplicationController:
class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
before_filter :check_session
private
def check_session
redirect_to login_path and return unless current_user?
end
def current_user?
!session[:username].blank?
end
end
SessionsController
class SessionsController < ApplicationController
def new
end
end
Upvotes: 0
Views: 1580
Reputation: 2034
You should use the before filter like this
before_filter :check_session, :except => [:new]
Upvotes: 0
Reputation: 3053
The issue is that, since your SessionsController
inherits from ApplicationController
, it actually inherits the before_filter
as well. This means you are not allowing someone to see the login page unless they are logged in, which is usually undesirable behavior. You want to skip this before_filter
on the login page:
class SessionsController < ApplicationController
skip_before_filter :check_session, only: :new
def new
end
end
Upvotes: 3
Reputation: 1466
I think you have problem in your routes. One way of solution is defining a root path for your app as:
root 'app_entry#index'
Then create a controller for it as given below:
class AppEntryController < ApplicationController
def index
if current_user
redirect_to 'controller_name/action_name'
else
redirect_to '/users/sign_in'
end
end
Hope this helps you.
Upvotes: 0