【问题标题】:Blocking Users From Specific Pages using Ruby on Rails and cancan使用 Ruby on Rails 和 cancan 阻止用户访问特定页面
【发布时间】:2013-12-30 21:44:46
【问题描述】:

我正在学习 Ruby on Rails,并正在研究使用 cancan 来帮助限制用户访问他们不应该拥有的操作和页面,这取决于他们是谁。我目前了解如何限制操作,但我很好奇是否有人可以帮助实际限制某些页面和唯一页面。

一个例子是我有一个管理员用户的主页和一个普通用户的主页,我将如何限制普通用户的管理页面?

谢谢,如果我做错了什么,任何指针都非常感谢。

【问题讨论】:

  • 您应该在控制器中使用before filter 以相应地限制访问。
  • 我已经看到了,但我想我不明白它是如何应用于特定网页的

标签: ruby ruby-on-rails-4 cancan


【解决方案1】:

如果你想使用cancan:

承认你在你的用户控制器中添加了一个方法admin_home

def admin_home
    @user = current_user
    authorize! :admin_home
end

您需要在 ability.rb 文件中指定您希望限制标准用户对 admin_home 的访问:

class Ability
    include CanCan::Ability

    def initialize(user)
        user ||= User.new # guest user (not logged in)
        if user.admin?
            #Authorize all actions
            can :manage, User
        else
            #authorize only self modifications and restrict access to admin_home
            can :manage, User, :id => user.id
            cannot :admin_home, User
        end
    end
end

您可以在官方 wiki 中找到有关 cancan 的大量资源,例如 https://github.com/ryanb/cancan/wiki/Defining-Abilitieshttps://github.com/ryanb/cancan/wiki/Authorizing-controller-actions

希望有帮助

【讨论】:

    【解决方案2】:

    注意:我只是给你一个例子,你不应该照原样使用它,但你可以有一个想法,你将如何放置你的逻辑。 p>

    class AdminsController < ApplicationController
      before_filter :check_admin, :only => [:index, :show]
    
      def index
        @admins = //whatever your query for this action
      end
    
      def show
        @admin = //whatever your query for this action
      end
    
      protected    
        def check_admin
          if(my_condition to check if user type is admin)
             {
               return true // or anything u want for ur admin user
             }
          else
             {
              //anything here when user is not admin
               1. you can redirect to users home page using redirect_to
               2. you can redirect to a specific page which shows "You are not authorized to see this web page"
             }
          end
        end
    end
    

    【讨论】:

    • 所以在页面顶部调用 check_admin 方法是我如何限制某些页面?
    • 在您的实际操作代码执行之前总是会调用过滤器... check_admin 将决定是否应该显示该页面....如果用户不是管理员,那么您将重定向到另一个位置.
    猜你喜欢
    • 2017-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-06
    • 1970-01-01
    • 2012-05-25
    相关资源
    最近更新 更多