How does web session work in this rails project?

459 views Asked by At

Introduction: I am building a facebook app which auto wishes happy birthday. I am building it in Rails and using a ruby API wrapper called fb_graph. The creator of fb_graph has graciously provided a working sample application fb_graph_sample

After playing around with it, I do not understand how the sessions/cookies work. For example, check out this code:

def require_authentication
  authenticate Facebook.find_by_id(session[:current_user])
rescue Unauthorized => e
  redirect_to root_url and return false
end

def authenticate(user)
  raise Unauthorized unless user
  session[:current_user] = user.id
end

Where does session[:current_user] comes from?

Under config/initializers/session_store.rb,

FbGraphSample::Application.config.session_store :cookie_store, :key => '_fb_graph_sample_session'

So, I look at the cookies for localhost which is where I am deploying it as using Chrome inspector tools, I see _fb_graph_sample_session with value, domain, path, expires, size, http, etc...

I still don't see how session[:current_user] comes about? Looking at the development.sqlite3 file, there is only 1 data for the facebook model. The id is 1 so, that leads me to believe that [:current_user] is 1 and the code is calling 'authenticate Facebook.find_by_id(1)'

Can someone please explain how session[:current_user] translate to 1? I read railstutorial.org chapter on signing-in-out and it creates a sessions controller but there is no sessions controller in the fb_graph_sample app.

Thanks,

1

There are 1 answers

0
RadBrad On BEST ANSWER

I get's set in the authenticate method:

  session[:current_user] = user.id

The app is using cookie based session store, when a user logs in a cookie (think of it as a special hash) is written to his browser. You use session pretty much as a hash, you can set as shown above, or get, i.e.

<%= "logged in as #{User.find(session[:current_user]).name}" %>