views:

623

answers:

2

I am using the CanCan authorization plugin (http://github.com/ryanb/cancan) for my application and it has worked great so far. I had it set like the following:

    class Ability
  include CanCan::Ability

  def initialize(user)
    user ||= User.new # guest user

    if user.role == "admin"
      can :manage, :all
    else
       can :read, :all 


    end
  end
end

This allows me to designate some users Admins and only they can access write functions. Now I want to take it another step and make it so people who are not logged in at all (current_user/user_session does not exist) cannot access some controllers of the site. I know it should be some sort of elsif with the middle part of the code for the user and the final else for everyone else. However, I have not been able to figure out the best way to go about setting this up. Is anyone familiar with CanCan and have some ideas on how to best approach this type of situation.

Thanks guys, every bit helps me learn more about rails and development in general!

+1  A: 

I'm not quite familiar with CanCan but this kind of logic belongs inside the specific controller. This is an extract of how i do it. I'm sure you get the point and can abstract it onto CanCan.

class ItemsController < ApplicationController
  before_filter :login_required
  # or if you only want to restrict it to some actions etc 
  # before_filter :login_required, :except => [:show]
  # or
  # before_filter :login_required, :only => [:edit]
end

class ApplicationController < ActionController::Base
  protected
    def login_required
       access_denied! unless current_user.logged_in?
    end
end

CanCan is for authorization not authentication. There's a difference ;)

Nils Riedemann
Okay, thank you very much, I think I was over thinking the problem. I can still use CanCan for my more complicated Admin logic and then just use something like what you wrote for pages I care whether someone is logged in or not. Thank a lot!
If this answer is enough for you, you should mark your question as answered using the link to the left of my post.
Nils Riedemann
A: 

I don't know if you're still looking for the answer to this, but it's not too hard. All you need is a condition that's false for a guest user. In your else block, put something like can :show, Controller do |controller| user.id.present? end

If the user's a guest, this will be false since it hasn't been saved, and therefore no access. If it's a logged in user, it'll be true, and so they'll get access.

yvonne