简体   繁体   English

限制某些登录用户的路由

[英]Restrict certain routes to logged in users

I'd like /something to only be accessible for logged in users, I have a current_user helper which returns a user id or nil if the current visitor is not logged in. 我希望/ something只对已登录的用户可用,我有一个current_user帮助器,如果当前访问者未登录,则返回用户ID或nil。

Where would be the best place to limit access to /something in the controller or can it be added as part of the routes? 限制对控制器中某物的访问的最佳位置在哪里?或者可以将其添加为路由的一部分?

You should handle that in your controller. 您应该在控制器中进行处理。 Routes decide where things go and then it is up to the controller to decide if you're allowed to go there. 路线决定事物的去向,然后由控制器决定是否允许您去那里。

You should have a general purpose authenticate method in your ApplicationController that checks if someone is logged in and redirects them to a login page if they're not. 您应该在ApplicationController中具有一个通用的authenticate方法,该方法可以检查是否有人登录,如果没有登录,则将其重定向到登录页面。 Then in your specific controller: 然后在您的特定控制器中:

class SomethingController < ApplicationController
  before_filter :authenticate

  def handler
    #...
  end
end

You can skip authentication for a specific handling with the :except option: 您可以使用:except选项跳过身份验证以进行特定处理:

before_filter :authenticate, :except => [ :this_one, :and_this_one ]

There are other options as well, see the filters section of the Action Controller Overview for details. 也有其他选项,有关详细信息,请参见“ 动作控制器概述 ”的过滤器”部分。

You must add in controller :before_filter and create action for that. 您必须添加controller:before_filter并为此创建操作。

:before_filter :authenticate 

def authenticate
  redirect_to(registration_path) unless current_user.nil?
end

Also you can use :only or :except filter options. 您也可以使用:only或:except过滤器选项。 Or i did not understant question? 还是我没有质疑?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM