How to pass sessions in Sinatra

121 Views Asked by At

I'm trying to implement sessions in my login process, but the session is not being passed from route to route while I'm using set :session_secret, SecureRandom.hex(64), but if I use set :session_secret, "secret" it works fine.

From my understanding I am not supposed to do that because it is not very secure.

Is there a way to use set :session_secret, SecureRandom.hex(64 and have it pass from route to route? Or, do I have to use set :session_secret, "secret"?

class MainController < Sinatra::Base
    register Sinatra::ActiveRecordExtension
    enable :sessions
    #set :session_secret, SecureRandom.hex(64)
    #set :session_secret, "secret"
    #set :session_secret, "secretsession"
    set :session_secret, "f650ed69344bab0084199bb8cc9aa5a1bd6756c3b57ad67023255af0fc3795057e"
    set :views, Proc.new { File.join(root, "../views/") }


get '/sessions_set' do 
        session[:foo] = 'hello'
        if session[:foo] == 'hello'
            binding.pry
            redirect '/fetch'
          else
            "Session value has not been set!"
          end
    end 

    get '/fetch' do
        binding.pry
        "You did it! session[:foo] value: #{session[:foo]}.\nMove on to Part II of this lab at '/second_exercise' "
      end


end 
1

There are 1 best solutions below

0
Eyeslandic On

If you run this every time it will create a different random code every time, making your session unusable essentially. You will have to run this piece of code at startup somehow for it to work.

:session_secret, SecureRandom.hex(64)

For a quick fix you could run this code in a console and just paste the output into your file as it seems you have already done. For a more secure way you could look into using environment variables.