Tom
Tom

Reputation: 34366

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?

Upvotes: 1

Views: 4620

Answers (2)

avy
avy

Reputation: 572

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?

Upvotes: 4

mu is too short
mu is too short

Reputation: 434675

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.

Upvotes: 4

Related Questions