通过ID检查用户权限的最佳方法是什么?

3
在Rails3应用程序中,我有许多带有user_id的模型 - 这样我就表明:它是由某个用户创建的。
例如:
current_user.id #=> 1
@item.user_id #=> 1
# this item created by user with id 1

我希望限制当前用户访问那些不是他/她创建的项目。类似于:
if @item.user_id == current_user.id
  #everything is fine
else
  #redirect somwhere with flash "You don't have an access here"
end

因为我有多个模型(和控制器来展示/编辑/删除),它们都涉及到用户ID,所以什么是最佳方法?

2个回答

4

使用CanCan

使用它,您可以像这样声明性地定义权限:

can :read, Project, :user_id => user.id

并且之后要执行这个规则:

def show
  @project = Project.find(params[:id])
  authorize! :read, @project
end

authorize!会引发异常,但您可以以更平和的方式进行检查:

<%= link_to 'Link to a project', @project if can? :read, @project %>

您可以拦截授权错误并在一个地方处理它们:
class ApplicationController < ActionController::Base
  rescue_from CanCan::AccessDenied do |exception|
    redirect_to root_url, :alert => exception.message
  end
end

0

最简单的方法是使用Active Record的has_many

也就是说,在控制器中,每当您加载Item时,只需这样说:

@item = current_user.items.find(params[:id])

这样你就不需要做任何工作来检查了。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接