Devise not working well with multiple subdomains on RoR3 application - ruby

I have seen a lot of questions about this topic, but a lot of them have contradictory information, and for some reason it didnt work for me.
I have:
a top level domain: i.e. lvh.me (development).
each user has subdomains: i.e. userdomain.lvh.me
The login form is in the top level domain: lvh.me
I want:
If an user logs in, the session needs to be shared between all the subdomains. I mean, the session needs to be active in lvh.me:3000/something and userdomain.lvh.me:3000
If an user logs out from lvh.me:3000/something it should work, and if the user logs out from userdomain.lvh.me:3000 it should work also.
I tried
Setting in an initializer the following:
MyApplication::Application.config.session_store :cookie_store, :key => '_mykey', :domain => :all
What happened?
I can login in lvh.me:3000, I am correctly redirected to lvh.me:3000/internalpage and if I go to subdomain.lvh.me:3000 it works great. I can also logout from lvh.me:3000/internalpage BUT if I try to logout from subdomain.lvh.me:3000 it doesn't work. The destroy action in Devise SessionsController is executed and everything, but the session doesn't die.
According to http://excid3.com/blog/sharing-a-devise-user-session-across-subdomains-with-rails-3/,
The trick here is the :domain option. What this does is sets the level
of the TLD (top level domain) and tells Rails how long the domain is.
The part you want to watch out for here is that if you set :domain =>
:all like is recommend in some places, it simply won’t work unless
you’re using localhost. :all defaults to a TLD length of 1, which
means if you’re testing with Pow (myapp.dev) it won’t work either
because that is a TLD of length 2.
So, after reading that I also tried
MyApplication::Application.config.session_store :cookie_store, :key => '_mykey', :domain => 'lvh.me'
What happened?
I can login in lvh.me:3000, I am correctly redirected to lvh.me:3000/internalpage and if I go to subdomain.lvh.me:3000 it doesn't work, i have no session there. If I go back to lvh.me:3000/internalpage my session has disappeared. What happened there?
What else?
Then, after reading rails 3.2 subdomains and devise I changed my initializer line to
MyApplication::Application.config.session_store :cookie_store, :key => '_mykey', :domain => '.lvh.me'
Note the "." before the domain name.
According to the post in SO:
This allows this cookie to be accessible across subdomains and the
application should maintain it's session across subdomains. May not be
100% what you are looking for but it should get you going in the right
direction.
What happened?
Nothing, it didn't work. Same behavior if compared with the last thing I tried.
I finally tried What does Rails 3 session_store domain :all really do? , creating a custom class to handle the cookies. But I had no luck.
Of course that I deleted all the cookies and temp files before each attempt. Also I changed the name of the cookie.
Any help? Thanks!

According to this guy here: Rails: how can I share permanent cookies across multiple subdomains? You need to set the domain manually? Googling around it looks like '.domainname.com' with the dot at the beginning really is the way to go.
If you inherit from Devise::SessionsController you can manually set it on create
class SessionsController < Devise::SessionsController
def create
# modify the cookie here
super
end
end
I am setting up a working example to test that out, I'll post back afterwards, cheers!
And here is my Edit
Forget tempering with the token on create. The problematic is this, you need to have the token domain set to '.lvh.me' that's all there is to it, but domain: '.lvh.me' just doesn't do anything. Here is my proof of concept and ultimately it boiled down to a single change inside a controller:
class HomeController < ApplicationController
def index
cookies[:_cookietest_session] = {domain: '.lvh.me'}
end
end
In Chrome the token would look like this
And that for subdomain.lvh.me, lvh.me and any other subdomain I tried. I can sign_in/sign_out from any and the session is created/destroyed accordingly.
Now I wouldn't advise doing it the way I did, I liked the middleware approach I think it would work just fine if setup properly. Let me know if you need further help on this.
Cheers!
Ok last thing
I went back and tried domain: :all because it really ought to work as you have expected. If I access lvh.me I get a cookie with .lvh.me but if I got to subdomain.lvh.me I get one that reads .subdomain.lvh.me

I think the issue is that :all adds a . to the subdomain.lvh.me so you would stay logged in with foo.subdomain.lvh.me which doesn't do you much good.
:all seems to work if your original login is from the root domain lvh.me and you then redirect to a subdomain. but you can't log in through a subdomain with it set that way.
MyApplication::Application.config.session_store :cookie_store, :key => '_mykey', :domain => '.lvh.me'
looks like the correct way to specify this.
Note:
Make sure you restart rails after making change.
Make sure you clear cookies out for your domain before testing again. You can leave remnant cookies behind that are confusing between tests.

Related

Implementing Remember Me in Padrino 0.11 with new admin interface

I'm trying to implement a 'Remember Me' feature in the new Padrino 0.11 Admin interface, but having a little bit of trouble due to the differences between it and Rails. Basically, I'm following along with http://railscasts.com/episodes/274-remember-me-reset-password.
I've managed to get the Remember Me and auth_token working handily, and I can see the cookie in the Dev console when I go to look at it. I am having a lot of trouble figuring out how to get the application to do autologin on the cookie when it is present though. I'm sure it's something stupid, but this is where I'm up to.
For instance, I've got the actual Remember Me creating an auth_token and setting it fine to the cookie (I can see it on localhost) in the dev console on Chrome via this in the sessions controller.
admin/controllers/sessions
post :create do
if account = Account.authenticate(params[:email], params[:password])
set_current_account(account)
if params[:remember_me]
response.set_cookie('da_app', value: account.auth_token,
expires: (Time.now + 1.year + 1.day))
end
flash[:success] = "You've successfully logged in as #{account.name}."
redirect url(:base, :index)
else
params[:email], params[:password] = h(params[:email]), h(params[:password])
flash[:error] = pat('login.error')
redirect url(:sessions, :new)
end
end
However, due to my inexperience with padrino, a little stumped as to where I'd put the bit of logic which triggers before an incoming request, checks for the cookie and then logs the user in. I tried the following, which is not perfect but which is definitely not working (though not sure why... =< ) and in fact, the code block to detect the cookie does not even seem to be firing (which seems pretty basic.).
admin/app.rb (not sure this is the right place for it actually)
before '/*' do
if request.cookies['da_app'].exists?
set_current_account(Account.find_by_auth_token(request.cookies['da_app']))
redirect url(:base, :index)
end
end
So, I'm sure it's probably dead simple to solve but a bit stumped on this one (and also, am really trying to avoid using a gem plugin like padrino-warden or the like at the moment and implement this from scratch as an exercise.).
(Also, bonus karma points on helping solve this one as I'm implementing this as part of some pro bono work for a global conservation charity.)

Sinatra not persisting session with redirect on Chrome

Sinatra is not persisting my session with a redirect on Chrome. It is creating an entirely new session and i'm losing all my previous session data.
As an example (similar to the Sinatra docs), i'm doing something like this:
enable :sessions
get '/foo' do
session[:user_id] = 123
session[:session_id] # "ABC", for example
redirect to('/bar')
end
get '/bar' do
# this is "DEF" when responding to Chrome (wrong),
# but "ABC" when responding to Firefox or Safari (right)
session[:session_id]
# this is nil when responding to Chrome (wrong),
# but 123 when responding to Firefox or Safari (right)
session[:user_id]
end
I'm thinking this has something to do with how the different browsers respond to handling the session after a redirect response. Has anyone seen something similar to this, or have any ideas on how to resolve this while still using sessions?
Thanks in advance!
Add this to your main app file:
use Rack::Session::Cookie, :key => 'rack.session',
:path => '/',
:secret => 'some-random-string'
With that added, you should be able to assign session['whatever'] and have it work as expected.
By doing enable :sessions you just get access to session per request.
Sinatra has no way to keep the reference to the previous call (your redirect) as it is treated as another request.
Thus, long story short:
set :session_secret, "SecureRandom.new(10) generated thing"
enable :sessions
always use enable :sessions with a secret, otherwise your session is recreated every time rack sees a request.
Please try to disable all custom cookie managament extensions is Chrome if any.
After that check headers in Developer tools → Network. Should see 'Cookie:' field.
I think that just because you didn't set :session_secret, refer to my answer on here

Rails 3.2.8 - Share Devise Sessions Across Subdomains with POW

I am trying to set up a simple subdomain-based blog in rails 3.2.8. Basically it will have sites, users (authenticated through Devise), and memberships to connect users to sites. I set up POW so that myapp.dev is working properly. Each site has a subdomain and I can navigate to the site#show action using the subdomains with no problems. My issue is that I can't get the Devise sessions to be shared across subdomains. Everything is working fine on my heroku app, but I would like to be able to test this locally.
When I add the following to session_store.rb, teh sessions seem to work across subdomains, but then I can't log out.
Appname::Application.config.session_store :cookie_store, :key => '_appname_session', domain: :all
When I change the end to domain: ".appname.dev" it doesn't work.
Any help would be greatly appreciated!
Make sure you clear your cookies and restart the app.
Appname::Application.config.session_store :cookie_store, :key => '_appname_session', domain: ".appname.dev"
domain: ".appname.dev" is the correct format for the domain option. The beginning period is important.

Sinatra session members "disappearing"

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.

How to set default cookie domain in Rails3

I want to set default cookie domain for my application to ".mydomain.com" to allow cookie session be preserved across subdomains. There are many places showing how to do it in Rails 2.x but these solutions doesn't work for Rails3. Anyone know how can I set it?
I've found the solution. Here it is:
Rails.configuration.session_store :cookie_store, {
:key => '_your_app_session',
:domain => ".domain.com"
}
This should go into config/initializers/session_store.rb. Works great for me.

Resources