简体   繁体   中英

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.

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. 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:

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.

:before_filter :authenticate 

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

Also you can use :only or :except filter options. Or i did not understant question?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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