subZero subZero - 6 months ago 13
Ruby Question

Sinatra clears session on post

enable :sessions
set :session_secret, 'secret'

post '/login' do
session[:loggedInUser] = jsondata['username'].to_s
puts session[:loggedInUser] + " is the session"
end


Everything is good at this point. When I read the session like this:

get '/debug' do
session.inspect
end


Its all there. But here comes the problem. When I go for another post request later on:

post '/foo' do
# do nothing
end


The session is cleared.

Why? Is this a bug?

EDIT

I have narrowed the problem down: I proxypass Sinatra through nginx, to
http://app.local/backend
- this is when the issue occurs. If I run Sinatra through
http://localhost:4567
it all works as expected.

SOLUTION

Use
Rack::Session::Cookie
instead of the default
enable :sessions
:

use Rack::Session::Cookie, :key => "rack.session",
:path => "/backend"
# etc


from the Sinatra FAQ:


If you need to set additional parameters for sessions, like expiration
date, use Rack::Session::Cookie directly instead of enable :sessions:

Answer

I do not see any issues at all. Here is my code. Try this and see if you still have that issue.

require 'sinatra'

configure do
  enable :sessions
  set :session_secret, 'secret'
end

get '/login' do
  session[:foo] = Time.now
  "Session value set."
end

get '/fetch' do
  "Session value: #{session[:foo]}"
end

get '/foo' do
  "Session value: #{session[:foo]}"
end

get '/logout' do
  session.clear
  redirect '/foo'
end

http://localhost:4567/login #=> Session value set.
http://localhost:4567/fetch #=> Session value: 2013-09-17 09:42:56 +0100
http://localhost:4567/foo #=> Session value: 2013-09-17 09:42:56 +0100
http://localhost:4567/logout #=>(redirects to) http://localhost:4567/foo #=> Session value: