I am trying to solve an issue I'm having with setting up admin on my site. Here is a simple version of my routes.
resources :users
resources :articles
resources :collaborators
end
resources :admin
Admin users are very similar to Collaborators, because they can edit and create Articles, but Admin has the ability to also c.r.u.d. Users, Collaborators, and Articles for every User. Collaborators can only c.r.u.d. Articles that are associated with the User they have been assigned to.
The part where this gets a little bit confusing is how to set up the controller and views that Admin uses for CRUD operations. As of now the way I am trying to implement it is to create separate CRUD views within admin/. The problem with this is that the functionality is so simimlar to a collaborator, I feel like it could be DRYer somehow.
Anybody know the most basic way to implement something like this? Thanks!
Update: I'd like to update this to say that it's super easy to google admin tools for rails. I'm more wondering how to implement this without an admin tool, or if that sounds like a bad idea, why?
The answer I came up with is to create Collaborators with an admin field true / false. I also set up CanCan and it's working pretty nicely.
Here is my CanCan ability.rb
def initialize(user)
if user.admin?
can :manage, :all
else
can :manage, Article, :id => user.article_id
cannot :index, Article
end
end
I just used "user" because it's more readable and shorter than collaborator and basically a user...
Try ActiveAdmin (http://activeadmin.info/). I think it is the most simplest way to build administrator backend for your application.
Related
I am writing a rails application for an organization. Every user may have 1 or more roles and can only access certain controller actions depending on those roles.
For example, only admins can create, destroy and update certain fields of Users. Also, there are Teams which each have a team leader, and only the team leader can update certain information about the Team (like the member list, for example). However, Admins are the one who assign the team leader in the first place.
The specific details of my scenario are not important, I merely hope I described the situation where there are many different roles and permissions.
My question is: what gem to use? My first thought was CanCan, but the last commit was almost a year ago and there is no mention of Rails 4 compatibility. Is there a currently maintained alternative?
Your first guess was right, use cancancan and you'll be good with it.
EDIT Jul 24, 2015
I've been using cancancan for a long time now and it was always working great. I've recently started working on a project where Pundit is used for authorization.
It is awesome. It prompts you to define the policy for each resource and it feels more natural than one bloated Ability class.
For bigger projects, I would definitely recommend Pundit.
To control access to actions I'd recommend Action Access, it boils down to this:
class UsersController < ApplicationController
let :admin, :all
let :user, [:index, :show]
# ...
end
This will automatically lock the controller, allowing admins to access every action, users only to show or index users and anyone else will be rejected and redirected with an alert.
If you need more control, you can use not_authorized! inside actions to check and reject access.
It's completely independent of the authentication system and it can work without User models or predefined roles. All you need is to set the clearance level for the current request:
class ApplicationController < ActionController::Base
def current_clearance_level
session[:role] || :guest
end
end
You can return whatever you app needs here, like current_user.role for example.
Although it isn't required, it bundles a set of handy model additions that allow to do things like:
<% if current_user.can? :edit, :team %>
<%= link_to 'Edit team', edit_team_path(#team) %>
<% end %>
Here :team refers to TeamsController, so the link will only be displayed if the current user is authorized to access the edit action in TeamsController. It also supports namespaces.
You can lock controllers by default, customize the redirection path and the alert message, etc.
It's very straightforward and easy, I hope you find it useful.
Something that was suggested to me that we are now using is the petergate gem. Easy to use and very clean looking with a great rails feel.
Works well with devise.
Here is some examples from the readme.
If you're using devise you're in luck, otherwise you'll have to add following methods to your project:
user_signed_in?
current_user
after_sign_in_path_for(current_user)
authenticate_user!
This comes in your User.rb. Adding more roles is as easy as adding them to the array.
petergate(roles: [:admin, :editor], multiple: false)
Instance Methods
user.role => :editor
user.roles => [:editor, :user]
user.roles=(v) #sets roles
user.available_roles => [:admin, :editor]
user.has_roles?(:admin, :editors) # returns true if user is any of roles passed in as params.
Controller access syntax.
access all: [:show, :index], user: {except: [:destroy]}, company_admin: :all
I have rails4 app. It has (among others) Client and Developer models. I also have Submission model.
I use activeadmin with cancan gems.
I try to make Submission's comments to be visible for both Client and Developer (which are related to certain submission), but when I check, developer only sees his comments and client correspondingly his. Assume, it has something to do with Ability class definitions. Here is mine (partially):
def developer_rules(developer)
can [:read, :create], ActiveAdmin::Comment
end
def client_rules(client)
can [:read, :create], ActiveAdmin::Comment
can :manage, Client, id: client.id
end
Has anyone faced anything similar? Would be grateful for any hints. Thank you!
UPD: SOLVED
Eventually, issue has nothing to do with Ability class.
ActiveAdmin shows comments separately for every namespace (even though these comment are associated to same resource), therefore the solution is to override this method
def self.find_for_resource_in_namespace(resource, namespace)
where resource_type: resource_type(resource),
resource_id: resource_id_cast(resource),
namespace: namespace.to_s
end
deleting last line namespace: namespace.to_s so that comments are shown independent of namespace.
In my rails application, my Users have many Projects through Participants.
Currently I am using CanCan for authorizations. I have done some research and can't quite figure out how to do the following.
In my ability.rb file I want to provide :manage abilities to to Users on Projects. Currently that looks like:
can :manage, Project if user.has_role? :silver
My Participants table has user_id and project_id. How do I only give those manage capabilities to users that are associated with a project via the participants table?
I am currently using the following as a solution. I would prefer using a solution native to devise or cancan.
In the model.
def is_participant?(participant)
self.participants.exists?(:project_id => participant)
end
And in my view.
<% if current_user.is_participant?(#project.id) %>
Are there are any authorization gems/examples for multi-tenancy applications?
I looked at CanCan and CanTango, but I wasn't able to find what I am looking for.
My app has Account, User, Relationship model. The relationship model has a relationship_type column which determines authorization level. Its value can be owner, moderator, editor, perhaps more in the future. Users can own/moderate many accounts, and an account can have many owners/moderators.
All the examples I found describe a single tenant application, whereas my app's authorization has to be scoped through the current account being viewed. A user can be a guest on one account and an owner of another, for example.
I'm starting to think my Relationship model is bad design and might have drawbacks, but I'm not sure what is a better alternative.
CanCan can indeed handle this because it lets you define arbitrary ruls. Your ability file might look like this:
def initialize(user)
can :read, BlogPost do |blog_post|
blog_post.account == user.account and user.relationship.in?([:owner, :moderator])
end
end
Try declarative_authorization, the authorization rules are defined in a single Ruby file using a DSL and you can define advanced rules based on objects' attributes and on the user role of course.
For example you can say something like this
role :moderator
has_permission_on :accounts do
to :manage
if_attribute :moderators contains {user}
end
end
declarative_authorization offer several methods you can use in models/controllers/views, for example in the account view you can use something like:
<% permitted_to? :update, #account do %>
<%= link_to 'Edit account', edit_account_path(#account) %>
<% end %>
You can have a look at the documentation and at the RailsCasts episode.
I'm using Ryan Bates' nifty authentication in my application for user signup and login. Each user has_many :widgets, but I'd like to allow users to browse other users' widgets. I'm thinking that a url scheme like /username/widgets/widget_id would make a lot of sense--it would keep all widget-related code in the same place (the widgets controller). However, I'm not sure how to use this style of URL in my app.
Right now my codebase is such that it permits logged-in users to browse only their own widgets, which live at /widgets/widget_id. What changes would I need to make to routes.rb, my models classes, and any place where links to a given widget are needed?
I've done Rails work before but am a newb when it comes to more complicated routing, etc, so I'd appreciate any feedback. Thanks for your consideration!
Look into nested routes. You could nest widgets inside users, like this:
map.resources :users do |users|
users.resources :widgets
end
Which would give you URLs like these:
/users/1/widgets # all of user 1's widgets
/users/1/widgets/1 # one of user 1's widgets
Check out the routing guide for more details.
The easiest would be to go with InheritedResources plugin which handles most of the legwork for you.
# routes:
map.resources :users do |user|
user.resources :widgets
end
class WidgetsController < InheritedResources::Base
# this will require :user_id to be passed on all requests
# #user will be set accordingly
# and widget will be searched in #user.widgets
belongs_to :user
end
# no changes required to the models