0

I have a simple rails 3.2 app with a Backbone.js front-end. I have the following before_filter and helper defined on my back-end:

# my before_filter placed in most controllers
def require_user
  unless logged_in?
    redirect_to '/#login'
  end
end

def logged_in?
  !!current_user
end

def current_user
  @_current_user ||= session[:user_id] && Appuser.find_by_id(session[:user_id])
end

This works great for restricting access to most actions to logged in users. However, I am also bootstrapping data into my Backbone.js collections with a <script> tag at the bottom of my main application template (haml):

!!!
%html{:lang => "en"}
  %head
    %title InfoUser
    = stylesheet_link_tag    "application", :media => "all"
    = javascript_include_tag "application"
    = csrf_meta_tags
    %script 
      $(document).ready(function(){ App.init(); });

  %body

    -# Layout markup

    :javascript
      projects.reset(#{Project.all.to_json})
      groups.reset(#{Group.all.to_json})
      users.reset(#{User.all.to_json})

  = render "layouts/templates"

The problem is, even if an unauthenticated user access the app and is immediately redirected to the login page, this bootstrapping script still gets added to the bottom of the page, and all the data shows up in the collections.

Is there a way in haml to check the status of the user, or is there another way I should handle bootstrapping that waits until the user is authenticated?

Siguza
  • 21,155
  • 6
  • 52
  • 89
jackwanders
  • 15,612
  • 3
  • 40
  • 40

1 Answers1

1

I'm not sure which part you want to execute only when the user is logged in but you can do it like this:

- if logged_in?
  -# code you want to run here

So for example,

- if logged_in?
  :javascript
    $(document).ready(function(){ App.init(); });
Dty
  • 12,253
  • 6
  • 43
  • 61
  • When I add `- if logged_in?` to /app/views/layouts/application.html.haml, I get a `NoMethodError in Home#index`, specifically `undefined method logged_in?' for ...`. Is there some kind of require statement I need to add to my haml file, or perhaps my `HomeController`? – jackwanders Jul 09 '12 at 23:25
  • `logged_in?` is available on the controller, not the view. You can pass an instance variable to the view from the controller, like `@logged_in`. – fdsaas Jul 09 '12 at 23:36
  • There are different ways to get your controller helpers into views. Here's a few - http://stackoverflow.com/questions/453762/nomethoderror-when-trying-to-invoke-helper-method-from-rails-controller – Dty Jul 09 '12 at 23:52
  • adding `@logged_in = logged_in?` to my `Home#index` action did the trick. – jackwanders Jul 10 '12 at 01:21