Skip to content

Applying permission model to search results

August 1, 2011

Enterprise applications usually have a role base access control (RBAC). The search results as well as the auto-completer suggestions must conform to the access control model. The recommended way to control the search results, using scoped_search, is chaining scopes. The scoped_search is a named scope (scope in rails 3), this means that it can be chained with other scopes in a natural way.

For example:

 scope :my_hosts, lambda {
where("owner_id = ?", User.current.id)
}
Host.my_hosts.search_for(query)

In the above code :my_hosts is the RBAC scope (defined in lines 1 to 3). In line 4 the search is chained to the RBAC scope.

For the auto-completer there is a new way of filtering the results in a similar way. In the Model we can define a scope called :compelter_scope , this scope should accept an options hash. The options hash is a way to pass parameters from the controller, such as the current user.

For example:
Model code:

scope :completer_scope, lambda { |options|
  where('owner_id = ?', options[:owner_id])
}

Controller code:

def auto_complete_search
  @items = Host.complete_for(params[:search], {:owner_id => User.current.id})
  render :json => @items
end

To read more about named scopes, here is a link to a detailed post on the subject: Skinny on scopes

Advertisements

From → Design, Developers

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: