Sinatra and session variables which are not being set
Asked Answered
M

1

11

For some reason, session variables are not being set in my app. I am using Sinatra 1.2.1.

Here is a piece of code:

module GitWiki
  class App < Sinatra::Base

    configure do
      enable :sessions

      set :app_file, __FILE__
      set :root, File.expand_path(File.join(File.dirname(__FILE__), '..', '..'))

      set :auth do |bool|
        condition do
          redirect '/login' unless logged_in?
        end
      end
    end

    helpers do
      def logged_in?
        not @user.nil?
      end
    end

    error PageNotFound do
      page = request.env["sinatra.error"].name
      redirect "/#{page}/edit"
    end

    before do
      content_type "text/html", :charset => "utf-8"
      @user = session[:user]
    end

    get "/login/?" do
      erb :login
    end

    post "/login" do
      user = User.get
      if user.authenticate(params[:username], params[:password])
        session[:user] = params[:username]
        p session # => {:user=>"root"}
      else
        # AZIZ!  LIGHT!
      end

      redirect '/'
    end

    get "/" do
      p session # => {}
      redirect "/" + GitWiki.homepage
    end

    # ... 
  end
end

As you can see, session[:user] is not being set, or rather the session hash is being reset after each request. Does anybody know what is going on please?

Milinda answered 12/4, 2011 at 7:33 Comment(0)
K
26

If you're using Shotgun, add the following line to the configure block:

set :session_secret, "My session secret"

To quote from rkh, Sinatra's current maintainer:

[Shotgun] will restart the server on every request, thereby regenerate the session secret and thus invalidate your sessions. This has been fixed in current master. Simple fix: set the session_secret option.

NOTE: This fix doesn't work if you use Rack::Session::Pool

Keyek answered 12/4, 2011 at 7:34 Comment(2)
From Sinatra's Doc: "However, since this secret will change with every start of your application, you might want to set the secret yourself..."Cooler
I like the "NOTE", do you happen to know who to fix this with Rack::Session::Pool?Clubwoman

© 2022 - 2024 — McMap. All rights reserved.