Duck Typed Cancan scenario - ruby-on-rails

Here's my Ability.initialize:
user ||= User.new # handle guest user
if user.has_role? :admin
can :manage, :all
elsif user.has_role? :moderator
can :read, :all
can :update, :all do |clazz|
clazz.managed_by? user
end
elsif user.has_role? :participant
can :update, :all do |clazz|
clazz.owned_by? user
end
can :read, :all do |clazz|
clazz.visible_to? user
end
else
raise "Role decoding in Ability fell through"
end
end
My intention is that the key domain classes [User, Round, Participant, Question and Program] all define an owned_by?, managed_by? and a visible_to? method. And that the rules for allowing one of them to be updated or viewed are applied uniformly.
But I believe that statements like:
can :update, :all do |clazz|
clazz.owned_by? user
end
Are not doing what I think because I don't think I even get to the clazz.owned_by? line.
Can someone straighten me out? I looked at the doc and couldn't really connect what it was saying with the technique I am using. Thank You!

I believe :all is simply a symbol and not an iterator through all classes. You can either list them all explicitly like I'm doing here or use this solution to get a list of all models: https://stackoverflow.com/a/516605/2033014
[User, Round, Participant, Question, Program].each do |klass|
can :update, klass, klass.owned_by?(user)
can :read, klass, klass.visible_to?(user)
end

Related

ROR Cancan - Right way to set permission for user

I am a new ROR developer. I want to set permission for each type of user with Cancan, from lowest to highest is: guest, member, editor, admin; with higher user has all permissions lower user has. My file ability.rb as below:
include CanCan::Ability
def initialize(user)
unless user
guest_can
else
if user.admin?
admin_can
elsif user.editor?
editor_can(user)
elsif user.member?
member_can(user)
end
end
end
private
def guest_can
can :read, Article
end
def member_can(user)
# member can do whatever guest can
guest_can
can :create, Comment
can [:update, :destroy], Comment, :user_id => user.id
end
def editor_can(user)
# editor can do whatever member can
member_can
can :create, Article
can [:update, :destroy], Article, :user_id => user.id
end
def admin_can
can :manage, :all
end
end
Could you please tell me if my code is good enough or can it cause potential problems? Thank you

How do I setup my CanCanCan permissions correctly?

I am a little confused about how to configure CanCanCan properly.
For starters, do I have to add load_and_authorize_resource to every controller resource I want to restrict access to?
This is what I would like to do:
Admin can manage and access all controllers and actions
Editor can read all, manage :newsroom, and can manage all Posts
Member can read every Post and can create & update Posts (not edit/delete/anything else), cannot access the newsroom. The difference between an update & edit post in our business rules is that an update is creating a new post that is a child post of the current post. So it isn't an edit. Just a new record with an ancestry association.
Guest can read every Post, but cannot create Posts nor access the Newsroom.
This is what my ability.rb looks like:
class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new # guest user (not logged in)
#Admin
if user.has_role? :admin
can :manage, :all
can :manage, :newsroom
# Editor
elsif user.has_role? :editor
can :read, :all
can :manage, :newsroom
can :manage, Post
#Member
elsif user.has_role? :member
can :read, :all
can :create, Post
can :status, Post
can :update, Post do |post|
post.try(:user) == user
end
#Guest
else
can :read, :all
can :create, Post
can :status, Post
end
end
end
In my routes.rb I have this:
authenticate :user, lambda { |u| u.has_role? :admin or :editor } do
get 'newsroom', to: 'newsroom#index', as: "newsroom"
get 'newsroom/published', to: 'newsroom#published'
get 'newsroom/unpublished', to: 'newsroom#unpublished'
end
What is happening though, is when I am logged in with a user that has not been assigned any roles (i.e. what I want to be a "Guest"), they can access the Newsroom.
When I try to edit a post with the role of :member, it gives me a "Not authorized to edit post" error (which is correct).
I just can't quite lockdown the Newsroom and I am not sure why.
You do not need to use load_and_authorize_resource in every controller. That is a convenience macro that does two things. First it assigns an instance variable with the record(s) assumed for the current controller and action. It then authorizes the resource. For some controller actions the first step might be wrong, so you want to load your resource and then authorize it manually. An example from the Railscasts episode about CanCan is like this:
def edit
#article = Article.find(params[:id])
unauthorized! if cannot? :edit, #article
end
You can also do it like in the example on the CanCan Wiki for authorizing controllers:
def show
#project = Project.find(params[:project])
authorize! :show, #project
end
Or you can just use authorize_resource and take care of loading it yourself. In the end, you must make sure that CanCan is used for authorization somehow (controller macro or in each action). Regarding your abilities, I think you want something like this:
class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new # guest user (not logged in)
#Admin
if user.has_role? :admin
can :manage, :all
# Editor
elsif user.has_role? :editor
can :read, :all
can :manage, :newsroom
can :manage, Post
#Member
elsif user.has_role? :member
can :read, :all
can :create, Post
can :status, Post
can :update, Post do |post|
post.try(:user) == user
end
#Guest
else
can :read, :all
cannot [:index, :published, :unpublished], :newsroom
end
end
end
And here's an example like how you might be able to authorize your newsroom:
class ToolsController < ApplicationController
authorize_resource :class => false
def show
# automatically calls authorize!(:show, :tool)
end
end
A last personal note about CanCan is that I wouldn't suggest it for new projects since it isn't actively maintained anymore and that I found it a bit counterintuitive when defining abilities. That said, CanCan is one of the most well-documented gems that I have worked with, especially the wiki has loads of examples and explanations.
can :read, :all
means user has permission to read all the resources of your app. It should be
can :read, Post
also add
cannot :manage, :newsroom
where you do not want access to newsroom. The order in which you specify permissions matters.
As others have already mentioned, 'load_and_authorize_resource' is optional. Only 'authorize resource' is needed to authorize all actions of a controller. If you skip these then you can 'authorize' individual controller actions.
Avoid using block for ability unless absolutely necessary. For instance if Post has a user_id in it then you could do
can :update, Post, user_id: user.id
Lastly, 'class => false' is used where you do not have a model backing your controller.
i.e you do not have a model called 'Newsroom' but you have a controller called 'NewsroomsController'.
For what it's worth, I had to setup my NewsroomController like this:
class NewsroomController < ApplicationController
authorize_resource :class => false
This is what the working version of my ability.rb looks like after I got it to work with the permissions I needed:
#Roles
#Admin
if user.has_role? :admin
can :manage, :all
# Editor
elsif user.has_role? :editor
can :manage, :newsroom
can :manage, Post
#Member
elsif user.has_role? :member
can [:read, :create, :status], Post
can :update, Post do |post|
post.try(:user) == user
end
#Guest
else
can [:read, :status], Post
end
For starters, do I have to add load_and_authorize_resource to every controller resource I want to restrict access to?
Yes.
What is happening though, is when I am logged in with a user that has
not been assigned any roles (i.e. what I want to be a "Guest"), they
can access the Newsroom.
From the guest role above:
...
#Guest
else
can :read, :all
can :create, Post
can :status, Post
end
This gives a guest read access to everything and the ability to create posts.
If you want your Guests to only be able to read posts it should be:
...
#Guest
else
can :read, Post
# can :status, Post # maybe you want this aswell
end

How can I define in ability model in cancan to allow user to edit the values with relations?

The following is the condition
I have users who belongs to one work and similarly category belongs to one work.
Now I want the user of that specific work to edit the categories that belongs to that work.
How can I specify this in ability model?
EDIT :
include CanCan::Ability
def initialize(user)
user ||= User.new # guest user
user.roles.each do |role|
role.name
if role.name == "admin"
can :read, User
can :create, User
can :edit, User
can :destroy, User
end
if role.name == "staff"
can :read, :all
can :create, :all
cannot :edit, Category
can :update, :all
can :destroy, :all
end
if role.name == "others"
can :read, :all
end
end
end
end
Untested, but this should do it:
can :manage, Category, :work_id => user.work_id
Reference: https://github.com/ryanb/cancan/wiki/defining-abilities
In the ability class you are passing only the user. You need to pass the category also in order to do,
can :manage, Category if user.work_id == category.work_id
Or you will have to iterate through like this( i ll not recommend it),
can :manage, Category if user.work_id == user.work.categories.first.work_id
This link shows how to send multiple params to your ability class.
https://github.com/ryanb/cancan/wiki/Accessing-Request-Data

cancan: Storing in the database vs accessible_by?

We have a UI that lets admins change permissions on our users. So we store these permissions in the database.
Our ability class is:
class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new # guest user
if user.role? :super_admin
can :manage, :all
else
if user.role? :live_trader
can :admin, LiveEvent
end
if user.role? :horse_trader
can :horse_admin, Event
end
if user.role? :channel_admin
can :manage, Channel
end
if user.role? :device_admin
can :manage, Device
end
if user.role? :ost
can :read, Customer.first
end
can do |action, subject_class, subject|
user.roles.find_all_by_action(aliases_for_action(action)).any? do |role|
role.authorizable_type == subject_class.to_s &&
(subject.nil? || role.authorizable_id.nil? || role.authorizable_id == subject.id)
end
end
# can always manage ourselves
can :manage, user
end
end
end
It works fine, except that we can't use accessible_by. We get:
The accessible_by call cannot be used with a block 'can' definition.
I don't see any other way of limiting result sets... Is this a bug or are we doing it wrong?
The error message says it all, really.
There's two ways use cancan using database permissions. One uses the 'can' block, the other uses explicit 'can' permissions. They achieve the same thing.
You can look at https://github.com/ryanb/cancan/wiki/Abilities-in-Database to see the two examples.
I'd say that you'd want to rewrite your 'can' block to:
user.roles.each do |role|
if permission.subject_id.nil?
can permission.action.to_sym, role.authorizable_type.constantize
else
can permission.action.to_sym, role.authorizable_type.constantize, :id => role.authorizable_id
end
end
HTH.

Restricting admin from destroying own account using cancan

Here is a snippet of my code from my ability class
if user.admin?
can :manage, :all
can :destroy, :all if != current_user
I am sure that you can figure out what I am trying to do here. I realize that destroy is included in manage and I am repeating myself there. Any suggestions?
EDIT Yjerem's answer was the correct one and I just changed it to fit my code. This is what it looks like.
if user.admin?
can :manage, :all
cannot :destroy, User, :id => user.id
As Yjerem also said, in cancan, ability precedence states that the ability defined lower down trump the ones over them so an admin can manage all except what is defined under it using the code above.
Read Ability Precedence, there's an example there just for you!
Basically what you want is the cannot method:
if user.admin?
can :manage, :all
cannot :destroy, User, :id => current_user.id
Because the cannot rule is below the more general one, it overrides it.
I would try something like this (assuming you have an Account/User model):
def initialize(user)
...
if user.admin?
can :manage, :all
can :destroy, Account do |account|
account.user != user # admin can destroy all Accounts/Users except his own
end
end
...
end

Resources