Omniauth Session expires when browser is closed

后端 未结 3 877
清歌不尽
清歌不尽 2021-02-16 00:01

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

3条回答
  •  情深已故
    2021-02-16 00:30

    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
    

提交回复
热议问题