我的rails3应用程序安装了declarative_authorization和inherited_resources gems。让我告诉你我的应用程序中的一些代码:
class Blog < ActiveRecord::Base
has_many :posts
has_many :memberships, :class_name => "BlogMembership"
has_many :subscribers, :through => :memberships, :source => :user, :conditions => "blog_memberships.membership_type = #{BlogMembership::SUBSCRIBER} or blog_memberships.membership_type = #{BlogMembership::AUTHOR} or blog_memberships.membership_type = #{BlogMembership::MODERATOR}"
has_many :authors, :through => :memberships, :source => :user, :conditions => "blog_memberships.membership_type = #{BlogMembership::AUTHOR} or blog_memberships.membership_type = #{BlogMembership::MODERATOR}"
has_many :moderators, :through => :memberships, :source => :user, :conditions => "blog_memberships.membership_type = #{BlogMembership::MODERATOR}"
end
class Post < ActiveRecord::Base
belongs_to :blog, :counter_cache => true
belongs_to :author, :class_name => "User", :foreign_key => "user_id"
end
class BlogMembership < ActiveRecord::Base
belongs_to :user
belongs_to :blog
# Membership types:
SUBSCRIBER = 0
AUTHOR = 1
MODERATOR = 2
end
我的授权规则:
authorization do
role :guest do
description "Not logged in users and users not assigned to any group"
##### Blogs and Posts
has_permission_on :blogs, :to => [ :read, :list ]
has_permission_on :posts, :to => [ :read, :feed ]
has_permission_on :posts, :to => :flag if User.current
end
role :admin do
description "Administrators"
has_omnipotence # Can manage all
end
role :moderator do
description "Blog moderators"
includes [ :guest, :blogger ]
has_permission_on :posts, :to => :manage do
if_attribute :blog => { :moderators => contains { user } }
end
end
role :blogger do
description "Blog authors"
includes :guest
has_permission_on :posts, :to => :create do
if_attribute :blog => { :authors => contains { user } }
end
has_permission_on :posts, :to => :manage do
if_attribute :author => is { user }
end
end
end
privileges do
# default privilege hierarchies to facilitate RESTful Rails apps
privilege :manage, :includes => [:create, :read, :update, :delete]
privilege :read, :includes => [:index, :show]
privilege :create, :includes => :new
privilege :update, :includes => :edit
privilege :delete, :includes => :destroy
end
在posts / index.html.haml中我使用
- if permitted_to? :create, :posts
.button.add-post
= link_to "New post", new_resource_path
和我的posts_controller
class PostsController < InheritedResources::Base
respond_to :html
belongs_to :blog
filter_access_to :all
end
看起来不错,但不起作用:(
测试用户拥有主持人的角色,主持人是其中一个博客的成员,但没有第二个博客的任何会员资格。
使用以下规则和代码,任何具有版主角色的用户都可以在任何博客中创建帖子。
你能告诉我 - 我需要改变什么才允许博客作者和版主将帖子发送到他们的博客而不是其他博客?
答案 0 :(得分:2)
不是那么优雅的方式,但我用以下方法解决了这个问题:
更改了posts_controller中的访问过滤器:
filter_resource_access:nested_in =&gt; :博客
添加了发布控制器的方法
保护
def new_post_for_collection @post = Blog.find(params [:blog_id])。posts.new 端
index.html.haml中的更改