【问题标题】:Rails - Allow access to controller action only to server sideRails - 仅允许对服务器端的控制器操作进行访问
【发布时间】:2017-06-14 08:17:37
【问题描述】:

我的 Rails 项目中有 usersprojects 脚手架。我还有一个admin 控制器和视图,只有管理员用户才能访问。我希望usersprojects 模型的indexcreate 控制器操作只能由admin 视图访问(使用render :partial > 'index'),但我不想让访问者访问该站点能够输入http://railsapp.host/users 并获得部分渲染。我如何做到这一点?

澄清一下,我的问题与用户角色无关。我有所有 require_admin 助手的 authlogic,但我什至不希望管理员用户能够直接从浏览器访问 usersindex 路由。实际上,我想将 index 控制器操作仅限于 admin#index 的视图代码,如下所示:

<%= render '/users/index' %>

【问题讨论】:

标签: ruby-on-rails controller


【解决方案1】:

最好的 rails 方法是在应用程序控制器中定义一个过滤器

 class UsersController < ApplicationController
   before_filter :check_isadmin?, :only => [:create, :index]
 end
 class ProjectsController < ApplicationController
   before_filter :check_isadmin?, :only => [:create, :index]
 end
 class ApplicationControlloller < ApplicationController
   def check_isadmin?
      current_user.admin?
    end
end

【讨论】:

  • 感谢您的回复。我的问题不清楚 - 我只是编辑了它。请参阅编辑。
【解决方案2】:

如果你为不同的用户使用角色,你可以检查管理员用户的角色然后渲染部分,例如:

<% if user.isAdmin? %>
  <%= render 'index' %>
<% end %>

【讨论】:

  • 感谢您的回复。我的问题不清楚 - 我只是编辑了它。请参阅编辑。
  • 我还不明白你想做什么,但是如果你想设置用户的能力,你可以试试Can Cangem。
  • Thanh,我有一个 users#index 控制器动作,它呈现一个部分。但是这个部分嵌入在admin#index 视图中。我不希望任何人能够输入https://localhost/users 并获得部分内容。实际上,我需要能够在我的用户控制器中辨别请求是来自直接在浏览器中输入的网址,还是来自admin#index 操作的呈现期间。
【解决方案3】:

好吧,我应该说我是一个相对的菜鸟。不过我想通了。我以为

<%= render '/users/index' %>

实际上是通过users#index 代码。我只是发现它只是在视图下调用部分而不通过控制器操作。所以我只是将它添加到users 控制器

def index
  redirect_to :controller=>'admin', :action=>'index'
end

这似乎达到了我所追求的目标。

感谢您的所有帮助。

【讨论】:

    【解决方案4】:

    补充对我有帮助的 Aayush Khandelwal 回答 before_filter 在 Rails 5 上被贬值。请改用 before_action。

    class UsersController < ApplicationController
       before_action :check_isadmin?, :only => [:create, :index]
    end
    

    在 :check_isadmin?如果为 false,则重定向到其他页面。

    def check_isadmin?
      if current_user == nil || !current_user.admin?
        redirect_to root_path
      end
    end 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-02-16
      • 2016-08-09
      • 2010-10-16
      • 2021-11-21
      • 1970-01-01
      • 1970-01-01
      • 2016-03-27
      • 1970-01-01
      相关资源
      最近更新 更多