VladRoker
VladRoker

Reputation: 40

Using current_user outside any action of custom controller in Ruby on Rails 3

I have to build site that only registered users can access. As a inexperienced RoR developer I tried to set up authentication system described in Railscasts episode #250 and planed to use Cancan as authorization system. While using Cancan check_authorization I had a problem with current_user variable, that is defined in private helper method in application_controller.rb:

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

And it looks like it is invisible to cancan check_authorization method in every other controller since it is placed outside any actions (thank you debugger gem).
Now any user (does not matter if he is logged in) can access login and registration pages (OK), but everyone cannot access any other action in controllers I have defined check_authorization (and this method must present in all of them)(not OK)
Question is: what would be the best way to fix this problem using rails conventions?

Alternative would be to use cancan authorize! method for every action, but it looks incorrect. Also, when I worked with devise gem, there was no problems like this, but for me it looks like using this authentication system is overly heavy for light projects like mine.

Upvotes: 1

Views: 1265

Answers (2)

Mandeep
Mandeep

Reputation: 9173

According to your question i think you want to authorise certain actions in your controller with the current_user method you have defined in application controller(correct me if i'm wrong). what you can do is use a before filter and define a private method in your controller to check if current user exists and if it doesn't then simply redirect to root page

class UserController < ApplicationController
  before_action :authenticate, except: [:index, :show] #list your actions in except array where you don't want to check for current user

  private

  def authenticate
    redirect_to your_path, notice: "You must login first" if !current_user  # if current user doesn't exist it will redirect to your path with notice
  end
end

Upvotes: 1

San
San

Reputation: 1954

Use a before_filter in your controllers like this:

before_filter :current_user

This will run the method before every action in the controller. You can include :only or :except to include or exclude certain methods if you need.

Upvotes: 0

Related Questions