【问题标题】:Rails 3 authorization with default authRails 3 授权与默认身份验证
【发布时间】:2011-12-25 13:14:23
【问题描述】:

我正在开发具有用户授权的应用程序。它有一个ListUser 类。身份验证由 Ryan Bates http://railscasts.com/episodes/270-authentication-in-rails-3-1

构建

我不确定授权过程。我读到了cancan gem。但我听不懂。

我想实现这个:

  1. 用户只能查看/编辑/删除自己的列表。
  2. 用户只能查看/编辑/删除自己的个人资料(用户类)。

我现在没有实现用户级别。无需猜测或管理。

如何在 listUser 控制器中使用 before_filter 方法和 current_user 实例?

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 authentication authorization


    【解决方案1】:

    由于您在应用程序控制器中定义current_user,这很容易。您可以在用户控制器中像这样使用before_filter

    class ItemsController < ApplicationController
      before_filter :check_if_owner, :only => [:edit, :update, :show, :destroy]
    
      def check_if_owner
        unless current_user.admin? # check whether the user is admin, preferably by a method in the model
          unless # check whether the current user is the owner of the item (or whether it is his account) like 'current_user.id == params[:id].to_i'
            flash[:notice] = "You dont have permission to modify this item"
            redirect_to # some path
            return
          end
        end
      end
    
      ###
    
    end
    

    你应该在 UsersController 中添加一个类似的方法来检查它是否是他的个人资料,他正在编辑。

    另外,请查看Devise,这是推荐用于身份验证的插件。

    【讨论】:

      【解决方案2】:

      为此,我不会使用设计。对于这个简单的用途来说,这是非常重要的。

      我会为公共视图创建一个单独的控制器并始终引用 current_user 请记住为 PublicController 中的操作创建路由

      class PublicController < ApplicationController
       before_filter :login_required?
       def list
        @list = current_user.list
       end
       def user
        @user = current_user
       end
       def user_delete
        @user = current_user
         # do your magic
       end
       def user_update
        @user = current_user
         # do your magic
       end
      
      # and so on...
      end
      

      【讨论】:

        猜你喜欢
        • 2019-03-02
        • 2011-09-27
        • 2016-08-31
        • 1970-01-01
        • 2016-02-15
        • 2014-02-23
        • 2012-03-25
        • 2011-03-12
        相关资源
        最近更新 更多