I am using sessions in my Facebook Canvas Application using Sinatra and Rack.
The error that occurs in Facebook Canvas is:
NoMethodError - undefined method `session' for #<Hash:0xa3ed0a0>:
/home/apoorv/.rvm/gems/ruby-1.9.2-p320/gems/sinatra-1.3.2/lib/sinatra/base.rb:170:in `session'
The problem is surely with Rack because when I run my application as follows:
ruby application.rb -p 3000
it does not display any error. I have tried installing rack version: 1.3.6 and 1.4.1, but the error persists.
I have also tried using the following code instead of enable :sessions
use Rack::Session::Cookie, :key => 'rack.session',
:domain => 'static.ak.facebook.com',
:path => '/',
:secret => 'change_me'
Do I need to upgrade/degrade to lower version of Rack or add some piece of Code to make this thing work?
edited
Also before coming across this issue I had an issue integrating my application in Facebook Canvas which was resolved by adding this line in config.ru:
set :protection, :except => [:remote_token, :frame_options]
Using env['rack.session'] instead of session[] in the POST request recieved from Facebook solved this issue. Hope this helps to solve such problems
Though it has not fully resolved complications because, now adding a redirect to code in the same POST callback displays: undefined method secure? error.
I have not been able to solve this issue, though what I did was to avoid the redirect thing and instead add a functionality to the controller to handle different requests.
Related
I started to build a website with padrino. At the moment the main class of my app is the simplest thing in the world:
class App < Padrino::Application
enable :sessions
get :index do
send_file 'public/view/index.html'
end
error 404 do
send_file 'public/view/errors/404.html'
end
end
So the views are simply htmls - the idea behind it is to use angularjs to render all the thingies provided by a rest api. I guess that's fairly standard.
My problem is - although it works fine for rendering the home page (localhost:3000/), the custom error doesn't work at all; let's say I try localhost:3000/test - the standard "Sinatra doesn’t know this ditty" page is rendered instead.
I'm running padrino 0.12.4 with WEBrick 1.3.1. What am I doing wrong here?
I believe what's going on here is that when you go to localhost:3000/test, your Sinatra app is looking for the "test" action under your App Controller. Obviously this action is not being found because it's not listed as a route! Therefore explicitly tell Sinatra to return a 404 page if the diddy wasn't found:
error Sinatra::NotFound do
content_type 'text/plain'
[404, 'Not Found']
end
I'm trying to make my Sinatra app's sessions more secure, and to do that I'd like to use the EncryptedCookie gem. Unfortunately, when I visit any page in my app, I get this error:
TypeError at /
no _dump_data is defined for class UnboundMethod
file: encrypted_cookie.rb location: dump line: 68
Here's my code:
configure do
use Rack::Session::EncryptedCookie,
:key => 'myapp.session',
:domain => 'myapp.com',
:path => '/',
:expire_after => 1200,
:secret => 'bigcrazysecretstringhere'
end
I tried using the EncryptedCookie gem with the same settings as shown above in a simple Sinatra app I made to test the gem, and it worked fine. There must be some other setting in my app that's interfering with the app, but I can't figure out what it might be. Has anyone out there experienced a similar issue?
(I've also tried starting the app with 'thin start', 'rackup config.ru', and 'ruby myapp.rb'- none of these made a difference.)
After banging my head against the wall for well over a week, I discovered the contractor who worked on the project before me had put
use Rack::Session::Pool
200 lines below the original
use Rack::Session::Cookie
I removed that and Encrypted Cookie worked fine. Lesson learned: Immediately abstract away everything you can when handed a 500 line Sinatra app. Then things can't hide from you.
I have a Grape-based API running as a rack application, using rack-cors to allow cross-origin requests, and Warden for authentication. CORS is working as expected, but not in cases where I invoke env['warden'].authenticate. In these cases, I get an "origin not allowed" response.
I believe this is due to the order of the middleware, but I'm relatively new to rack applications. I found some information describing a similar problem with an example of how to make this work in Rails, by forcing the order of the middleware using config.middleware.insert_before Warden::Manager, Rack::Cors do ... but I don't know of a non-Rails equivalent.
The following is a simplified approximation of my config.ru:
require File.expand_path('../application', __FILE__)
use Warden::Manager do |manager|
manager.default_strategies :password
end
use Rack::Cors do
allow do
origins '*'
resource '/*', :headers => :any, :methods => [:get, :post, :options, :put]
end
end
run application
I've tried swapping the order of the use directives, but either way I get same "origin not allowed" response from methods that use warden. Part of my problem is that I'm not clear on what determines the order of the middleware in rack applications.
Is my hunch that the order of the middleware is causing this problem feasible? It seems like I'm missing something fundamental. I'd like to get rack-cors and Warden to play nicely or to find another solution to allow CORS. I tried explicitly sending the Access-Control-Allow-Origin header but Warden seems to wipe that out as well.
Had exactly the same (rather annoying) thingie, ended up with doing this on my one:
on a before do block,
header 'Access-Control-Allow-Origin', '*'
header 'Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT'
(You may want to tweak according to RACK_ENV or such...)
Seems to work. Note this is not a full CORS implementation(of course its not) but i'll wait for that rack-cors gem fix...
HTH
I've successfully troubleshooted an issue with session members not being available even though they were set and would like to know why it's happening. My situation can be described as:
Sinatra app using :session.
Using oAuth to authorise users and in the process setting a :ret_url session member so that the app knows where to come back to after auth.
Server is unicorn on Cedar stack (Heroku)
This works perfectly whilst running locally but the :ret_url session member was completely disappearing from the session on Heroku. I found that if I removed this code it fixed the problem:
before do
cache_control :public, :must_revalidate, :max_age => 60
end
Question 1: I'm guessing that my cookie was being cached without the :ret_url value and that's why it was breaking?
Question 2: I was setting the session member as shown in the route condition code below, is this the wrong place to do it?
# redirect users to login if necessary
set(:auth) do |access_token|
condition do
if request.request_method == 'GET'
session[:ret_url] = request.path_info
end
redirect '/' unless user_logged_in?
end
end
I'd like to use cacheing and still have my cookie be valid.
Hard to see what is going on without knowing all details, but there is a simple rule that you are most probably violating: do not use http caching on actions that are supposed to do something (other than just show page). When http caching is on, you browser does not even try to re-load the page and renders it from browser cache.
Cookies are not cached anywhere, the only thing cache_control does is setting CacheControl http response value
In your case the best thing you can do is to add list of routes that have no-action pages to your before block:
before '/my/static/page' do
cache_control :public, :must_revalidate, :max_age => 60
end
Most probably you will have very limited set of routes where you can benefit from http caching
A chap by the name of Ari Brown (waves at Ari), who is not a member here but deserves the credit for this answer, pointed me at the right solution, which is, as per the Sinatra FAQ, to not use enable :sessions but to use Rack::Session::Cookie as per
use Rack::Session::Cookie, :key => 'rack.session',
:domain => 'foo.com',
:path => '/',
:expire_after => 2592000, # In seconds
:secret => 'change_me'
I've added this into my config.ru and all is well.
I also noticed over in this post the alternative suggestion to set :session_secret, 'change_me' and, indeed, to do this via an environment variable, namely:
$ heroku config:add SESSION_KEY=a_longish_secret_key
then in your app
enable :sessions
set :session_secret, ENV['SESSION_KEY'] || 'change_me'
Obviously you can use the environment variable strategy with the Rack::Session::Cookie approach too. That's the way I went as it offers more flexibility in configuration.
The reason these work is that the cache controller middleware is farming requests out to multiple server instances and without setting a session secret it's just making one up per server, and thus breaking the sessions.
I am running a sinatra app and have a testing suite setup using rspec 2.7.0 and webrat 0.7.3 (both the most recent versions). I have an extensive set of tests for all of my request actions and it seems to be working fine. Today I discovered Sinatra's redirect back request-level helper and implemented it in a couple of areas of my application that were rendering forms with get requests which were taking parameters.
The nice thing about the redirect back helper is that if I have an action say:
get '/login' do
#used_var = params[:var]
haml :login
end
Which renders a form, I can have validation on the post request receiving the form:
post '/login' do
# pretend User.authenticate pulls back a user entry from the database if there
# is a valid username/password combination
unless User.authenticate(params[:username], params[:password]).nil?
redirect '/content'
else
flash[:notice] = "Invalid username/password combo"
redirect back # will redirect back to the get '/login' request
end
end
And if the form doesn't validate properly, it will redirect back to the page with the from and retain any parameters that were passed in without me having to worry about storing it to a session variable. The only problem is that rspec doesn't seem to want to play nicely with the redirect back helper. i.e. if I have a spec action that does this:
it 'should redirect to login when invalid username/password combo is received.' do
get '/login', :var => 'value'
fill_in 'username', :with => 'invalid_username'
fill_in 'password', :with => 'invalid_password'
click_button 'Submit'
last_response.should be_redirect; follow_redirect!
last_request.url.should include("/login")
end
The spec fails to pass because for some reason it seems that rspec or webrat isn't picking up on the redirect back helper and is instead redirecting the request back to the root url for my application ('/').
What I want to know is whether there is a way to get rspec to redirect to the proper location in these instances? The actual application functions as expected when I test it with my browser (it redirects me to the first page with parameters), but the rspec tests don't pass properly.
try to pass :referer => '/login' to your requests, so redirect_back can know where the actually 'back' is
Apparently this was a bug in rack, and it appears to have been fixed with the release of rack 1.3.0. I tested this spec with rack 1.2.5 (most recent version prior to 1.3.0 release), and it failed, but upon upgrading to 1.3, it started passing.
After some digging around, pretty sure that this pull request (here is the commit) was the change that fixed it.
So it is no longer an issue in rack ~> 1.3.