mitch
mitch

Reputation: 2245

Rails, devise, acl

I have followed this tut http://railsapps.github.com/tutorial-rails-bootstrap-devise-cancan.html I want to do something like this:

before_filter :authenticate_user!
before_filter :authenticate_VIP!
before_filter :authenticate_admin!
before_filter :authenticate_somerole!

I have tables: roles, users, user_roles and I don't want to create another table (rails g devise VIP create another table).

I want to have methods authenticate_ROLE. How to do this ?

Upvotes: 0

Views: 1646

Answers (1)

Thanh
Thanh

Reputation: 8634

I have three table, Users, Roles, and RoleRelationships (or role_users, it's up to you)

This is my Role table:

class Role < ActiveRecord::Base
  attr_accessible :name
  has_many :role_relationships
  has_many :users, through: :role_relationships
end

Role table will have name column for roles, like: "admin", "teacher", "vip" (as you want).

And this is User table:

class User < ActiveRecord::Base
  devise ...
  has_many :role_relationships
  has_many :roles, through: :role_relationships
end

and my RoleRelationship table:

class RoleRelationship < ActiveRecord::Base
  attr_protected :role_id, :user_id

  belongs_to :user
  belongs_to :role
end

I set up my app one user can have many roles, you can set up your way. So, i have a role?(role) method in my user.rb, like this:

def role?(role)
  return role == RoleRelationship.find_by_user_id(self.id).role.name
end

Then in my abilities files, i define abilities of users:

def initialize(user)

  user ||= User.new # guest user

  if user.role? "teacher"
        can :read, Course
        can :manage, Topic, user_id: user.id
        can :create, Topic
  else  user.role? "admin"
        can :manage, Course
  end

So, teacher will only read Course, and admin can CRUD Course. To do that, i use method load_and_authorize_resource in my CoursesController:

class CoursesController < ApplicationController

  load_and_authorize_resource

  before_filter :authenticate_user!
  ...
end

Finally, in my views, i used code like this:

<% if can? manage, @course %>
   Only admin can work, see what happen here.
<% end %>

So, as you see, teacher only can read Course so they can't see or do what admin can do, in this case, is create course or edit course.
This is what i built in my online test app, you can reference and do the same for your app.

Upvotes: 3

Related Questions