Reinier
Reinier

Reputation: 162

Not staying signed in with omniauth-facebook

I've followed Ryan's cast on signing in with omniauth-facebook and the signing in works great.

The problem I'm having though is staying signed in. Right now I'm signed in until I close the browser window. If I open my browser again and go back to my website I'm signed out. Same goes for other people on other machines and other Facebook accounts.

I'm not too familiar with the workings of sessions and Facebook authentication so it's hard for me to analyse what is going wrong exactly.

Maybe some of you know what is going on? Thanks in advance!

My code:

application_controller:

def current_user
  @current_user ||= User.find(session[:user_id]) if session[:user_id]
end
helper_method :current_user

sessions_controller:

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

user.rb:

def self.from_omniauth(auth)
  where(auth.slice(:provider, :uid)).first_or_initialize.tap do |user|
    user.provider = auth.provider
    user.uid = auth.uid
    user.name = auth.info.name
    user.email = auth.info.email
    user.pic_url = auth.info.image
    user.oauth_token = auth.credentials.token
    user.oauth_expires_at = Time.at(auth.credentials.expires_at)
    user.save!
  end
end

omniauth.rb:

OmniAuth.config.logger = Rails.logger

Rails.application.config.middleware.use OmniAuth::Builder do
  provider :facebook, CONFIG[:facebook_app_id], CONFIG[:facebook_app_secret], scope 'email', display: 'popup'
end

Upvotes: 2

Views: 135

Answers (2)

Mike Szyndel
Mike Szyndel

Reputation: 10593

It's straight in the Devise wiki

on signup in SessionsController do

remember_me(user)

and be sure to have :rememberable passed as Devise option in your user model.

Side note - I think you use quite outdated flow, right now encouraged solution is to have OmniauthCallbacksController I think.

Upvotes: 1

Naveen Kumar
Naveen Kumar

Reputation: 200

May be problem here is when you close the browser the session is getting expired.

Why can't you use devise gem for signing the user.

If you use devise gem for your User table, you will get an option called "Remeber Me", you can set this flag as true when the user is loggedin.

For more info on devise refer - https://github.com/plataformatec/devise

This may solve your issue.

Upvotes: 1

Related Questions