Shotgun sinatra session[:value] not avaiable in different routes

48 Views Asked by At

Take this code (modular Sinatra app)

#application_controller.rb

require 'sinatra/base'
require "sinatra/activerecord"
require 'bcrypt'
require "sysrandom/securerandom"
include BCrypt
enable :sessions

    class Application < Sinatra::Base
    
        post '/identifier' do 
            user = User.find_by_email(params['email'])
            if user && user.authenticate(params[:password]) 
                session[:babyami] = user.prenom 
                puts "after identification: #{session[:babyami]}"
                redirect to '/'
            else
                erb :'principal/identifier' 
            end
        end


        get '/' do
            puts "at root: #{session[:babyami]}"
        end

and in the console, when using shotgun :

== Shotgun/Thin on http://127.0.0.1:9393/
D, [2020-12-02T08:48:30.672731 #8992] DEBUG -- :   User Load (0.3ms)  SELECT "users".* FROM "users" WHERE "users"."email" = $1 LIMIT $2  [["email", "[email protected]"], ["LIMIT", 1]]
after identification : Moshe
127.0.0.1 - - [02/Dec/2020:08:48:30 +0100] "POST /identifier HTTP/1.1" 303 - 0.2239
at root: 
127.0.0.1 - - [02/Dec/2020:08:48:31 +0100] "GET / HTTP/1.1" 200 - 0.0045

But is works when I use rackup!

$ rackup
2020-12-02 08:51:46 +0100 Thin web server (v1.8.0 codename Possessed Pickle)

D, [2020-12-02T08:52:11.639346 #9165] DEBUG -- :   User Load (0.4ms)  SELECT "users".* FROM "users" WHERE "users"."email" = $1 LIMIT $2  [["email", "[email protected]"], ["LIMIT", 1]]
after identification : Moshe
::1 - - [02/Dec/2020:08:52:11 +0100] "POST /identifier HTTP/1.1" 303 - 0.2519
at root: Moshe
::1 - - [02/Dec/2020:08:52:11 +0100] "GET / HTTP/1.1" 200 - 0.0009

Any reason why sessions function correctly when launching rackup, but not when using shotgun? How to enable sessions correcly using shotgun?

1

There are 1 best solutions below

0
On

May this be useful.

shutgun restarts the server at each request, so the session gets lost. The workaround is to set en ENV variable as explained here : sinatra docs (don't forget to reboot)

and require that secret in the app like so:

enable :sessions
set :session_secret, ENV.fetch('SESSION_SECRET') { SecureRandom.hex(64) }

See here too : google discussion