1

I have a main Controlller:

class MainController < Sinatra::Base
  set :views, File.expand_path('../../templates', __FILE__)
  enable :sessions
  helpers AppHelper::Main
end

and a I have a couple of other controllers which inherit from MainController and has its own routes configured with map on config.ru

AuthController

class AuthController < MainController
  # Code above
  get_login = lambda do
    redirect '/' if session[:admin]
    erb :login, :layout => false
  end
  get '/login', &get_login
  # Cobe below
end

config.ru

# code above
map('/') { run AppController } # Another inherited controller...
map('/auth') {run AuthController }

on AppHelper::Main I have the following function which I used on a template routed from AppController

def authenticated?
  session[:admin]
end

on AuthController I can change session[:admin], but when I try to access session[:admin] on a template which uses authenticated? function it just return nil, as it was not changed. My question is: sinatra session share values through Apps?

Hugo Hernani
  • 165
  • 1
  • 10

1 Answers1

1

My question is: [does] sinatra session share values through Apps?

Yes, session cookies should be shared by different apps given the same key.

# config.ru
require_relative "app.rb"

map('/') { run AppController } # Another inherited controller...
map('/auth') {run AuthController }

# app.rb
require 'sinatra/base'

class MainController < Sinatra::Base
  #set :views, File.expand_path('../../templates', __FILE__)
  enable :sessions
  #helpers AppHelper::Main

  get '/' do
    "#{self.class.name}: value = " << session[:value].inspect
  end

  get '/:value' do
    session['value'] = params['value']
    "#{self.class.name}: value = " << session[:value].inspect
  end
end

class AuthController < MainController

end

class AppController < MainController

end

Using this I am able to access the data in either controller regardless of which one set it. I think your problem is elsewhere. I would suggest using encrypted_cookie and setting that up in the config.ru to be used by the apps, it may make a difference while increasing the security of the cookies.

ian
  • 12,003
  • 9
  • 51
  • 107
  • Thank you, @iain. After I saw [this question](http://stackoverflow.com/questions/18844863/sinatra-clears-session-on-post) and answers for it I could solve the problem. – Hugo Hernani Jul 26 '15 at 12:48