【问题标题】:Users in a company can only view projects within their company in Rails..?公司中的用户只能在 Rails 中查看他们公司内的项目..?
【发布时间】:2011-12-22 08:09:21
【问题描述】:

我有三个模型:用户、组织和项目。

组织拥有_many 用户(具有不同角色)和用户属于_to 组织。

用户拥有_许多项目,项目同时属于用户和组织(通过将@project.organization_id = current_user.organization_id 放入控制器的def create 方法中)。

我将此位放入我的projects_controller.rb 文件中,以确保登录的用户只能查看与其组织关联的项目。

def index
    @projects = Project.where(organization_id:current_user.organization_id)
end

然而,这一切只是对 current_user 隐藏其他项目。如果他输入http://localhost:3000/projects/3(属于另一个组织的另一个用户的项目),他仍然可以访问它。

我应该在 projects_controller 的 def show 部分添加什么来阻止这种情况发生?我已经破解了几件事,但我无法在没有任何错误的情况下正确完成。如果可能的话,我也不想使用 CanCan。

我试着放了一个

before_filter :require_project_belong_to_organization, :only => [:show]

def require_project_belong_to_organization
   @project = current_user.projects.find(params[:id])
end

但这仅在是创建它的用户时才返回结果。我需要其他用户也能够查看它,只要他们在同一个组织中。

【问题讨论】:

    标签: ruby-on-rails authorization


    【解决方案1】:

    试试cancan

    【讨论】:

    • 没有CanCan是否可以做到?
    • 至少停止访问部分。我不确定“all_resources_this_user_can_access_from_this_model”是否也在其中。
    • 好的。我硬着头皮选择了CanCan。花太多时间在这件事上太少了!
    • @Reactormonk 你是怎么用康康舞做到这一点的,因为我试图做同样的事情?谢谢。
    • @Frank004 4 年了,cancan 好像停产了。
    【解决方案2】:

    在控制器中使用 before_filter 并检查项目的用户是否与 current_user 相同

    【讨论】:

    • 我关心的不是项目的用户,而是项目的organization_id必须和current_user的组织id一致。
    【解决方案3】:

    我会首先在项目模型中创建一个函数authorized?。确保 current_user 对模型可用。

    authorized?
      self.organization_id == current_user.organization_id
    end
    

    然后在控制器中:

    def show
      @project = Project.find(params[:id])
      if @project
        unless @project.authorized?
          flash[:danger] = 'not authorized'
          redirect_to.... 
        end
      else
        flash.now[:danger] = 'Project was not found'
      end
    end
    

    【讨论】:

    • PunditCanCanCan 这样的 gem 可以让这种方法变得更容易。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-17
    • 1970-01-01
    • 1970-01-01
    • 2018-10-20
    相关资源
    最近更新 更多