从头开始为用户提供Railscast授权 [英] Railscast authorization from scratch for users
问题描述
这是我根据编写的授权代码Railscast#386 .
问题在于,该块可在除user_controller
之外的所有控制器上运行.换句话说,任何用户都可以在其他任何用户上触发edit
和update
动作,即使分配给它的块与偏爱edit
和update
动作的块相同.
The problem is that the block works on all controllers except for user_controller
. In other words, any user can triger edit
and update
actions on any other user, even though the block given to it is the same as that of favors edit
and update
actions.
def initialize(user)
allow :users, [:new, :create, :show]
allow :sessions, [:new, :create, :destroy]
allow :favors, [:index, :show]
if user
allow :users, [:edit, :update] do |usr|
usr.id == user.id
end
allow :favors, [:new, :create]
allow :favors, [:edit, :update] do |favor|
favor.user_id == user.id
end
allow :acceptances, [:create, :update] do |acceptance|
!acceptance.has_accepted_acceptance?
end
end
end
我们非常感谢您的帮助:)
Any help is highly appreciated :)
推荐答案
您已经将(user)
传递给权限类.通过再次调用
You are already passing in the (user)
to the permission class. By calling it again in
if user... do |user|... end
您正在重新初始化传入的用户,使其成为nil
.然后,您尝试对controller#action授予零用户权限,在这种情况下,涉及用户帐户的任何操作.
you are re-initializing the passed-in user, making it nil
. You then try to give a nil user permissions on the controller#action, in this case anything involving the user's account.
Ryan Bates在涉及其他模型的权限中包含一个阻止的原因是因为尚未将模型实例传递给权限类.这就是为什么您看到以下内容的原因:
The reason Ryan Bates includes a block in permissions involving other models is because the model instance hasn't been passed to the permission class. That is why you see the likes of:
allow_action :topics, [:new, :create, :index]
allow_action :topics, [:edit, :update, :show] do |topic|
topic.author_id == user.id
end
allow_attr :topic, [:title, :content]
上面的这一位授予用户可能或已经创建的所有主题的权限.
This bit above grants permissions on all the topics the user may or has created.
解决方案,取出所有可重新初始化(user)
的内容,然后重试.
SOLUTION Take out anything that re-initializes the (user)
and then try again.
allow_action :users, [:edit, :update]
allow_attr :users, [:email, :invite_token, :name, :surname, :password, :password_confirmation]
注意,根据Railscast中Ryan的建议,我已将allow
操作重命名为allow_action
.我也将allow_param
方法重命名为allow_attr
,因为我们习惯于使用attr_accessible.
NOTE I have renamed the allow
action to allow_action
, as per Ryan's suggestion in the Railscast. I also renamed the allow_param
method to allow_attr
since we are used to using attr_accessible anyway.
这篇关于从头开始为用户提供Railscast授权的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!