26

I feel like I'm missing something obvious here, and I'm hoping that as soon as I post this someone will shame me with the google search link I was missing :-)

enable :sessions

get '/logout' do
  # What goes here to kill the session?
end
ecoffey
  • 3,423
  • 4
  • 23
  • 22

2 Answers2

45

Just use

session.clear

to destroy the session.

Ry-
  • 218,210
  • 55
  • 464
  • 476
Jonas Fagundes
  • 1,519
  • 1
  • 11
  • 18
  • From the OP example it's clear (`enable :sessions`) that they are using Sinatra or a similar ruby framework, yet they asked about deleting the session using `Rack::Session::Cookie` directly. Does the solution provided in this answer applies to that, or is Sinatra/Rails specific? According to http://stackoverflow.com/questions/10451392/how-do-i-set-get-session-vars-in-a-rack-app `#session` is a method specific to Sinatra/Rails/... and plain rack applications don’t have it. If this is true then, does anybody know what's the correct rack-only way to deal with this? – Redoman Oct 07 '15 at 15:16
  • not working for me, tried it a couple of times. I have a very simple app using `enable :sessions` – Ohad Perry Oct 08 '15 at 12:40
  • @jj_ Nope, `sinatra` and `rails` use rack middleware. – Jonas Fagundes Nov 16 '15 at 13:31
3

It depends how you create your session. Simply you have to nulify session entry. Here is simple example, how to create and destroy sessions.

  get '/login' do
    session[:username] = params[:username]
    "logged in as #{session[:username]}"
  end

  get '/logout' do
    old_user = session[:username]
    session[:username] = nil
    "logged out #{old_user}"
  end

You can also check this example: https://gist.github.com/131401

tjeden
  • 2,019
  • 1
  • 13
  • 19
  • 2
    Hmm, I had tried that, but the rack.session cookie still exists after I "log out". – ecoffey Nov 23 '10 at 22:39
  • @ecoffey are you sure its the same cookie? If you use `session.clear` it'll likely be a new session, but the old one will havw been destroyed. Nil-ing session key(s) might keep the original cookie but be devoid of any value(s). – xentek Feb 28 '14 at 03:50