1

I'm using omniauth-github gem and I noticed that the user is kept in a session cookie:

SessionsController:

def create
  user = User.from_omniauth(env["omniauth.auth"])
  session[:user_id] = user.id
  ...
end

Do you know an easy way to persist the session after the browser is closed?

I know it could be achieved with an integration with Devise: https://github.com/plataformatec/devise/wiki/OmniAuth:-Overview ...but I'm hoping for a simpler solution.

Thanks


Solution:

A 'token' column is added to the User model and then:

class User < ActiveRecord::Base
  before_save :generate_token
  def generate_token
    self.token = SecureRandom.urlsafe_base64
  end
end

class SessionsController < ApplicationController
  def create
    user = User.from_omniauth(env["omniauth.auth"])
    cookies.permanent[:token] = user.token
  end
end

class ApplicationController < ActionController::Base
  def current_user
    @current_user ||= User.find_by_token(cookies[:token]) if cookies[:token]
  end
end
Martin Petrov
  • 2,633
  • 4
  • 30
  • 44

2 Answers2

1

You have to use a cookie. A session ends when the browser is closed. A cookie persists even after that.

Try this:

    def create
      ...
      cookies[:user_id] = user.id
      ...
    end

Actually this answer is what you're looking for.

Community
  • 1
  • 1
Agis
  • 32,639
  • 3
  • 73
  • 81
  • aha, but is this safe? i mean, is this the right way to do it? – Martin Petrov Jun 02 '12 at 14:30
  • Using a cookie is definitely *the* way to do it. For security concerns, you should read the official [security guide](http://guides.rubyonrails.org/security.html#sessions). – Agis Jun 02 '12 at 14:32
  • I have the exact same problem right now. I need to keep users signed in after they have closed their browser. I get this error when I do cookie instead of session though: "undefined local variable or method `cookie' for #". Is this the way to go? Some people integrate devise to and use the rememberable-functionality. – Holger Sindbaek Jun 02 '12 at 19:20
  • It seems that it should be cookies and not cookie, but it is still not working for me. Not saving the user after I exit the browser. – Holger Sindbaek Jun 02 '12 at 19:44
  • Yes I've fixed the typo. It's `cookies`. You can use `<%= debug(params) %>` in your view to see if the cookie is actually saved. However I've updated my initial answer with a link that should help you out :) – Agis Jun 03 '12 at 08:57
0

Here is how it works for me:

def google_oauth2
  @user = User.from_google(google_params)

  if @user.persisted?
    @user.remember_me = true
    sign_in @user
    ........
  end
end

There is another way to do it

Sasha Stadnik
  • 502
  • 1
  • 6
  • 16