2012-06-02 65 views
1

我使用omniauth,github上的寶石和我注意到,用戶保存在一個會話cookie:Omniauth:如何在瀏覽器關閉後保持用戶登錄?

SessionsController:

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

你知道一個簡單的方法來堅持在會議結束後的瀏覽器關閉?

我知道它可以通過與Devise的集成來實現:https://github.com/plataformatec/devise/wiki/OmniAuth:-Overview ...但我希望有一個更簡單的解決方案。

感謝


解決方案:

A '令牌' 列被添加到用戶模型,然後:

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 

回答

1

你必須使用一個Cookie。會話在瀏覽器關閉時結束。即使在此之後,cookie仍然存在。

試試這個:

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

其實this answer是你在找什麼。

+0

aha,但是這是安全的嗎?我的意思是,這是正確的做法嗎? –

+0

使用cookie絕對是*做到這一點的方法。出於安全考慮,您應該閱讀官方的[安全指南](http://guides.rubyonrails.org/security.html#sessions)。 – Agis

+0

我現在有完全相同的問題。我需要讓用戶在關閉瀏覽器後登錄。但是,當我執行Cookie而不是會話時,出現此錯誤:「」未定義的局部變量或方法Cookie。這是要走的路嗎?有些人將設計集成到並使用可記憶的功能。 –

相關問題