2007-05-08
每天一剂Rails良药之Role-Based Authorization
关键字: Rails Role-Based Authorization
我们的系统往往并不只是靠登录这么简单来控制权限,今天我们来看看基于角色的授权
假设我们的系统已经建立了昨天的users表
1,migration
2,model
3,application.rb
4,layout
如果我们的某一个controller或者action不想要check_authentication和check_authorization这两个filter,我们可以skip掉:
但这只能精确到controller和action级别的权限控制
如果我们想控制对models实例的访问权限,可以参考Bruce Perens的ModelSecurity
假设我们的系统已经建立了昨天的users表
1,migration
class AddRolesAndRightsTables < ActiveRecord::Migration
def self.up
create_table :users_roles, :id => false do |t|
t.column :user_id, :integer
t.column :role_id, :integer
end
create_table :roles, :do |t|
t.column :name, :string
end
create_table :roles_rights, :id => false do |t|
t.column :role_id, :integer
t.column :right_id, :integer
end
create_table :rights do |t|
t.column :name, :string
t.column :controller, :string
t.column :action, :string
end
end
def self.down
drop_table :users_roles
drop_table :roles
drop_table :rights
drop_table :rights_roles
end
end
2,model
class User < ActiveRecord::Base has_and_belongs_to_many :roles end class Role < ActiveRecord::Base has_and_belongs_to_many :users has_and_belongs_to_many :rights end class Right < ActiveRecord::Base has_and_belongs_to_many :roles end
3,application.rb
class ApplicationController < ActionController::Base
layout 'standard'
before_filter :check_authentication,
:check_authorization,
:except => [:signin_form, :signin]
def check_authentication
unless session[:user]
session[:intended_action] = action_name
redirect_to :controller => :admin, :action => signin_form
return false
end
end
def check_authorization
user = User.find(session[:user])
unless user.roles.detect{|role|
role.rights.detect{|right|
right.action == action_name && right.controller == controller_name
}
}
flash[:notice] = "You are not authorized to view the page you requested"
request.env["HTTP_REFERER"] ? (redirect_to :back) : (redirect_to home_url)
return false
end
end
end
end
4,layout
<% if flash[:notice] %>
<div class="errors">
<% flash[:notice] %>
</div>
<% end %>
如果我们的某一个controller或者action不想要check_authentication和check_authorization这两个filter,我们可以skip掉:
class HomeController < ApplicationController
skip_before_filter :check_authentication, :check_authorization
def index
render :text => "A page that doesn't require a signin or any rights"
end
end
但这只能精确到controller和action级别的权限控制
如果我们想控制对models实例的访问权限,可以参考Bruce Perens的ModelSecurity
发表评论
- 浏览: 612372 次
- 性别:

- 来自: BJ

- 详细资料
搜索本博客
我的相册
screenshot
共 1 张
共 1 张
最近加入圈子
最新评论
-
深入了解Java ClassLoader ...
当我对字节码编译不知所措的时候,发现了这个帖子 谢谢楼主,目前正在学习ASM C ...
-- by ytzhsh -
Rails里如何结合Exceptio ...
收藏了,小工具,好东西.
-- by yangzhihuan -
使用coderay和railscasts ...
不错,很爽,如果能显示成textmate那样的就好了。
-- by carlosbdw -
Axis2快速上手指南
看得很累,希望楼主写个HelloWorld.谢谢
-- by zznj1123 -
使用coderay和railscasts ...
javaeye自己用的是什么highlight什么的吗?
-- by qichunren






评论排行榜