dwmcc
dwmcc

Reputation: 1074

How to disallow user actions in CanCan

In my ability.rb file, how can I set it so that only defined users can do things, else (an undefined/not logged in user) cannot do anything?

Example:

def initialize(user)
    user ||= User.new #not logged in user
    if user.admin_user?
        can :manage, :all
    else
        #can't do anything. Cannot view, edit, or update.
    end
end

Thanks!

Upvotes: 0

Views: 80

Answers (2)

James
James

Reputation: 1908

You could try a simple conditional set in your initialize function:

# app/models/ability.rb
def initialize(user)
  if user && user.admin_user?
    # Abilities for registered admin users
    can :manage, :all
  elsif user
    # Abilities for registered users
    can :read, :all
  else
    # Abilities for no user
  end
end

When initialize is called, user will likely (depending on your authentication solution) be nil for not logged in users, which will trigger the last branch.

Upvotes: 0

Calvin
Calvin

Reputation: 8765

I've never really used CanCan, but I looked over the docs, and I don't think you need to explicitly define what the user can't do.

You should just be able do something like this in your controller:

if cannot? :destroy, @project 
  # redirect the user or do something else to disallow access
end

cannot? should return true if the user wasn't assigned a role that has any abilities defined. Conversely can? would return false.

Upvotes: 1

Related Questions