views:

132

answers:

1

Hi,

I'm a rails noob and first time poster here and am using declarative authorization in order to implement role base access restriction in a small timesheet app I am writing.

In one of my views, specifically the index.html.erb for my time_registers needs to display more information if the user who is logged in has the admin role assigned.

In the beginning I was just checking that user would be the one with id == 1

<% if @current_user.id == 1 %>

but now I'd like to be able to not restrict it to the user with id==1 but to allow any user who has had the admin role assigned to view a bit more in the index.html.erb file.

A bit how the model is set up with declarative_authorization

class User < ActiveRecord::Base
  has_many :assignments

class Role < ActiveRecord::Base
  has_many :assignments
  has_many :users, :through => :assignment

class Assignment < ActiveRecord::Base
  belongs_to :user
  belongs_to :role

My Authorizations file looks like this:

authorization do

  role :usuarios do
    has_permission_on :users, :to => [:index, :show, :new, :create, :edit, :update]
  end

  role :reghoras do
    has_permission_on :time_registers, :to => [:index, :show, :new, :create, :edit, :update]
    has_permission_on :users do
      to :show
      if_attribute :id => is {user.id}
    end
  end

  role :contactos do
    has_permission_on :contacts, :to => [:index, :show, :new, :create, :edit, :update]
    has_permission_on :users do
      to :show
      if_attribute :id => is {user.id}
    end
  end

  role :admin do
    has_permission_on :authorization_rules, :to => :read
    has_permission_on [:time_registers, :contacts, :users, :roles], :to => [:index, :show, :new, :create, :edit, :update, :destroy]
  end

  role :guest do
    has_permission_on [:time_registers, :contacts], :to => [:index, :show]
  end

end

Well, I am not sure what else would be needed to answer this question, so feel free to request more information.

+2  A: 

OK, so I had looked throught the example and not found anything about this. But after checking the API again I did find something that worked.

I exchanged all instances of

<% if @current_user.id == 1 %>

for

<% if has_role?(:admin) %>

Just in case someone happens to come by wanting help on this same issue, the following is the page in the API where I found the function mentioned above:

http://www.tzi.org/~sbartsch/declarative_authorization/master/

There's not much description to it, but looking at the source one can see that it checks if the current user has a specific role passed to the function. That's how I figured to just use the function directly.

I wonder if what I am doing is actually the right way to go about implementing an admin page or if I maybe should implement the admin view separate from the view for the general users and not in the same file??. So far I have not found any discussion on how to do this.

Andreas Hennig