user1234
user1234

Reputation: 43

Keep users from accessing pages in Rails app if they're not logged in

I'm fairly new to Rails and am building a webapp to learn. I currently have the webapp working to accept new users and log them in. However, I want to block access to pages other than the login page when users aren't logged in. I've searched for hours and nothing I have found has worked. I don't want to use to Devise. Here is my code:

Application controller:

class ApplicationController < ActionController::Base
   protect_from_forgery
   include SessionsHelper
   before_action :logged_in_user
end

Session Helper:

module SessionsHelper

  def current_user
    @current_user ||= User.find(session[:user_id]) if session[:user_id]
  end

  def logged_in?
      !current_user.nil?
  end

  # Confirms a logged-in user.
  def logged_in_user
     unless logged_in?
        flash[:danger] = "Please log in."
        redirect_to 'name of login page'
     end
  end

end

Currently, the page just reloads over and over (because the user isn't logged in) and the page times out. What am I doing wrong?

Upvotes: 0

Views: 931

Answers (1)

Mahmoud Sayed
Mahmoud Sayed

Reputation: 668

when you use before_action in the ApplicationController the specified action will run before any action in all controller that inherits ApplicationController unless you skip it by skip_before_action.

In your case you need either to apply before_action in ApplicationController and use skip_before_action before login action in for example in the SessionsController or you can only use before_action in all other controllers instead of ApplicationController to specify when you need them to run.

class SessionsController
  skip_before_action :logged_in_user, only: :login

  def login
  end
end

Also remember to handle when a user is already logged in and he tries to visit the login page.

Upvotes: 1

Related Questions