Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Omniauth Session expires when browser is closed

In my rails 3 app I use Omniauth for the user authentication part (fb/twitter).

Actually I follow this:

https://github.com/RailsApps/rails3-mongoid-omniauth

https://github.com/RailsApps/rails3-mongoid-omniauth/wiki/Tutorial

But, when I close the browser session expires and I need to login again. How can I keep the session for returning users?

Any help would be greatly appreciated!

like image 662
Lamp Avatar asked Feb 06 '12 22:02

Lamp


3 Answers

What you want is not difficult, you only have to set a permanent cookie when the session is created and then retrieve this value when you set the current user.

In your ApplicationController, just change your current_user method to:

def current_user
  return unless cookies.signed[:permanent_user_id] || session[:user_id]
  begin
    @current_user ||= User.find(cookies.signed[:permanent_user_id] || session[:user_id])
  rescue Mongoid::Errors::DocumentNotFound
    nil
  end
end

And in your SessionsController, modify your create to set the cookie if user wants to:

def create
  auth = request.env["omniauth.auth"]
  user = User.where(:provider => auth['provider'], 
                    :uid => auth['uid']).first || User.create_with_omniauth(auth)
  session[:user_id] = user.id
  cookies.permanent.signed[:permanent_user_id] = user.id if user.really_wants_to_be_permanently_remembered
  redirect_to root_url, :notice => "Signed in!"
end
like image 120
David Avatar answered Oct 22 '22 07:10

David


Devise offers this functionality through its Rememberable module. OmniAuth integrates easily with it through the (you'd never guess it) OmniAuth module. It's even mentioned in the second link you posted!

like image 33
andrew.rockwell Avatar answered Oct 22 '22 07:10

andrew.rockwell


Please make sure the cookie policy that your rails app follows does have sensible settings for your use case (see the link in my comment above). All I can imagine right now (knowing what I know, sitting where I sit) is that the cookie(s) ha(s/ve) properties that are suboptimal/undesirable in your context.

Please check the cookie settings in a browser debug/development tool such as firebug, firecookie or the chrome development tools.

Sorry, that's all I can come up with given my knowledge of the problem. Feel free to contact me again with more details on your cookie- and testing-setup.

My 2Cents.

like image 1
mkro Avatar answered Oct 22 '22 08:10

mkro