views:

54

answers:

3

I know that I can have a session after the user login. Also, I created a helper method called "current_user". I don't want to other people which are not signed in can get access to the page. Apart from making doing this, how can I do?

I can do this to not allow people the get access to the content, but I don't want the user within login see the blank page too.

<% if current_user%>
My Content
<% end %>
+2  A: 

Make a before_filter that checks if the current_user variable is set, and redirects the user to some other place (root, signup page, something) if it is not. Something like this:

class ApplicationController < ActionController::Base
  def login_required
    redirect_to('/') if current_user.blank?
  end
end

class MyController < ApplicationController
  before_filter :login_required, :only => :action_aviable_only_for_logged_in

  def action_aviable_only_for_logged_in
    ...
  end
end
Toms Mikoss
+1  A: 

Authentication is a delicate area and it is one of the aspects where developers keep reinventing the wheel. I'd suggest you use a ready to use library or plugin to do so. In particular I would recommend using Authlogic plugin.

It works as a plugin so no generated code nor intrusive stuff goes into your app.

In answer to your question, the access limit verification should go in the controller, by using a before_filter and checking the action they are going to execute is allowed. (The filter method is passed the controller instance and is hence granted access to all aspects of the controller and can manipulate them as it sees fit)

However, using the plugin I mentioned above this would be as easy as

before_filter :require_user, :except => [:list]

this would require login for all actions in the controller except for the list action

Miquel
A: 

I think before_filter is the way to go if access controls is the only issue being dealt with. I dont think authlogic really helps you there. But there are other access controls gems like cancan by Ryan Bates which seems light weight and pretty easy to use. Then there is declarative authorization. However if you have a large app I think before_filters give you greater control. You may have seperate modules that provide access controls to each utility.

Sid