Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 4 - Devise not binding session

I recently upgraded my app to Rails 4. I have been authenticating the users with and only with a custom openid port over omniauth.

Controller (Omniauth Callbacks)

class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
  def openid
    @user = User.where(provider: auth_hash["provider"], uid: auth_hash["uid"]).first_or_initialize
    @user.name = auth_hash["information"]["name"]
    @user.email = auth_hash["information"]["email"]
    @user.save!
    sign_in_and_redirect @user, :event => :authentication
  end

  protected

  def auth_hash
    request.env['omniauth.auth']
  end
end

Routes

devise_for :users, :controllers => { :omniauth_callbacks => "users/omniauth_callbacks" }

devise_scope :user do
  get 'sign_in', :to => 'devise/sessions#new', :as => :new_user_session
  get 'sign_out', :to => 'devise/sessions#destroy', :as => :destroy_user_session
end

root :to => "users#front"

[...]

Issue

After logging in correctly at the extern service, the user is being redirected back to OmniauthCallback#openid. The user is getting created correctly without any issues. After that the user is redirected to root without any problems. But at that point he is still not logged in!

My sessions are stored in the Database correctly aswell. I do not get any errors, it simply does not work as it should at sign_in_and_redirect @user, :event => :authentication. How can I bind the session to the user properly?

Update

Using Cookies to store Sessions instead of the database doesn't solve.
Using sign_in @user and reloading page doesn't solve.
Using @user.save instead of @user.save! doesn't solve.

I'm grateful for any ideas.

like image 837
Miiller Avatar asked Mar 26 '26 19:03

Miiller


1 Answers

I finally figured something out. I added this line to my oauth callback method before "sign_in_and_redirect @user":

session[:user_id] = @user.id

After that, current_user is set properly. Hope this helps somebody.

like image 104
jshou Avatar answered Mar 28 '26 09:03

jshou