ruby-on-rails - CanCan 在应该阻止访问时却没有阻止

标签 ruby-on-rails ruby authorization cancan

当我以其他用户身份登录时访问 users/1/edit 不会引发 AccessDenied 错误,我不知道为什么:

  authorize_resource only: [:edit, :update]
  def edit
    @user = User.find(params[:id])
  end
  def update
    @user = User.find(params[:id])
    if @user.update_attributes(params[:user])
      redirect_to @user
    else
      render 'edit'
    end
  end

能力等级:

class Ability
  include CanCan::Ability
  def initialize(user)
    user ||= User.new

    can :read, :all
    can :create, User
    can :create, Group

    can :update, User, id: user.id
  end
end

如果我将 authorize_resource 更改为 load_and_authorize_resource 那么它会按预期工作。但这肯定不应该相关吗?

最佳答案

您的代码仅授权用户访问编辑和更新操作,而不是 @user 对象

您必须像这样手动授权对象

试试这个,

def edit
  @user = User.find(params[:id])
  authorize! :update, @user
end

def update
  @user = User.find(params[:id])
  authorize! :update, @user
  if @user.update_attributes(params[:user])
   redirect_to @user
  else
   render 'edit'
  end
end

关于ruby-on-rails - CanCan 在应该阻止访问时却没有阻止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12860146/

相关文章:

mysql - 从 has_one 关联中调用一个值

ruby-on-rails - 创建新的 Rails 应用程序时加载错误

ruby-on-rails - 当允许请求方法但无法完成操作时,RESTful 资源的正确状态代码是什么

ruby-on-rails - 在 Rails 中覆盖实例方法

Ruby:当我使用递归查找素数时出错

asp.net - .NET Forms Authentication using IIS8.0 Express (vs2013) - 401.2。 : Unauthorized: Logon failed due to server configuration

oauth-2.0 - 使用 PKCE 的授权代码流如何比没有 client_secret 的授权代码流更安全

javascript - sinatra javascript 调用

cryptography - 用什么?电子签名?

ruby - Ruby 中如何将方法名转换为符号?