public
Description: acts_as_authenticated Ruby on Rails authentication system
Home | Edit | New

Smart Login Logout Box

When the user is not logged in, I would like to have the sidebar on my site showing a login box.

Once the user has logged in, the login box should change to
“Hello, username!” Followed by a logout button.

I’m new here, so I’m having a devil of a time figuring out in layouts/application.rhtml to tell if the user is logged in or not without throwing errors.

I thought it would look something like:

<% if [ logged in ] -%>
<%= render(:partial => “account/logout” >
<
else -%>
<%= render(:partial => “account/login” >
<
end -%>

But I can’t seem to figure out how to tell if the user is logged in…

<% if not logged_in? >
<
= start_form_tag :controller => ‘account’, :action => ‘login’ >


<= text_field_tag ‘login’ >



<= password_field_tag ‘password’ >


<= submit_tag ‘Log in’ >


<= end_form_tag >
<
= link_to(“Register for an Account”, :controller => ‘account’, :action => ‘signup’) >
<
= link_to(“Forgot your password?”, :controller => ‘account’, :action => ‘forgot_password’) >
<
else >
<
= start_form_tag :controller => ‘account’, :action => ‘logout’ >
Logged in as:
<
= current_user.first_name > <= current_user.last_name%>
<%= submit_tag ‘Log out’ >


<
= end_form_tag >
<
end %>

Which I then render from application app/views/layouts/application.rhtml

<%= render(:partial => “account/smart_login”) %>

Answer:
To check if someone is logged in:

<% if !current_user.nil? %>

or use:

<% if logged_in? -%>

Note: The answer only works if the controller method behind the view is actually filtered for login data. If you use

before_filter :login_required, :only => [ …

in your controller, only those methods that are in the list will have current_user and logged_in? set. The other methods will gladly throw parse errors if you try and get at the methods. In other words, checking at the view level is useless, since you won’t get the view at all unless you are logged in.

Question: So is there any possible way of checking if the user is logged in in pages that aren’t required for login? (i.e. home page). I don’t want the user to think he needs to re-log in just because he’s on the home page (especially if I set cookies).

Answer: Session variables are always available in views, so this should work:

<% if session[:user].nil? >
Not logged in.
<
else >
Logged in.
<
end %>

——————
My related question, how can I modify the above code to bring the user back to the page they were on?

Answer: The “return_to” field is set in the session. You can use the store_location method from the Authenticated System class to set it where appropriate.

Last edited by gundestrup, Fri Oct 24 03:49:32 -0700 2008
Home | Edit | New
Versions: