Skip to content

Instantly share code, notes, and snippets.

@geekq
Created December 25, 2009 17:39
Show Gist options
  • Save geekq/263676 to your computer and use it in GitHub Desktop.
Save geekq/263676 to your computer and use it in GitHub Desktop.
# Demonstrates a secure usage of sessions in Sinatra
# for authentication and notices.
require 'rubygems'
require 'sinatra'
configure :production, :test do
use Rack::Session::Cookie,
:key => 'rack.session',
:domain => '.example.com', # use a wildcard with leading
# dot and at least two dots in total
:path => '/',
:expire_after => 10*60*60, # in seconds - for persistent cookies -
# survives browser restart
:secret => 'd81ca50470b5bc80e9' # please change this secret; you i
# can use the same secret in your multiple applications to share
# the state between all your applications, that run in the same
# wildcard defined domain group
end
configure :development do
use Rack::Session::Cookie,
:key => 'rack.session',
# do not use the localhost domain here, wildcard '.localhost' also
# does not work (likely) because of 'two dots rule'
# :domain => 'localhost', # localhost for development
:path => '/',
:expire_after => 10*60*60, # In seconds
:secret => '93b7e7ef35bc0b08d'
end
get '/' do
"<form method='post'>
<h2>Please type in your name</h2>
<input name='username' type='text'>
<input type='submit' value='submit'>
</form>"
end
post '/' do
puts params[:username]
# The Rails like flash notice will be stored in a cookie on the client
# side and will survive the redirect
session[:notice] = "Hello #{params[:username]}"
puts 'in post / ' + session.inspect
redirect '/next_step'
end
get '/next_step' do
puts 'in next_step ' + session.inspect
"<h1>Next step</h1><div>Flash: #{session[:notice]}</div>"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment