简体   繁体   中英

Rails + Devise: if user_signed_in? not working

I first discovered an issue where it didn't appear as if the user is getting logged in with this logic:

_header.html.erb :

<% if user_signed_in? %>
          <li><%= link_to "Log out", destroy_user_session_path, method: :delete %></li>
        <% else %>
          <li><%= link_to "Sign in", new_user_session_path %></li>
        <% end %>

Then I tried adding this to application_controller.rb :

before_filter :authenticate_user!

And I kept getting looped back to the login page (even with valid credentials).

It appears as if my user sessions aren't working — although I can see on my RailsAdmin console that the sign in count and last sign in date are showing as if they are logging in.

Here's my user.rb :

class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :omniauthable, :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable

  belongs_to :company

  has_and_belongs_to_many :productlines
end

And my routes.rb :

Rails.application.routes.draw do

  mount RailsAdmin::Engine => '/admin', as: 'rails_admin'
  devise_for :users, :controllers => { :omniauth_callbacks => "omniauth_callbacks" }

  root 'productlines#index'

end

And omniauth_callbacks_controller.rb :

class OmniauthCallbacksController < Devise::OmniauthCallbacksController 
  def google_oauth2
    @user = User.from_omniauth(request.env["omniauth.auth"])
    if @user.persisted?
      flash.notice = "Signed in through Google"
      sign_in_and_redirect @user
      return
    else
      session["devise.user_attributes"] = @user.attributes
      flash.notice = "You are almost Done! Please provide a password to finish setting up your account"
      redirect_to new_user_registration_path
    end
  end
end

Update: Here is my application_controller.rb

class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  skip_before_filter :verify_authenticity_token, :if => Proc.new { |c| c.request.format == 'application/json' }
  before_filter :productline

  def productline
    @productlines = Productline.all 
  end

end

Every time I sign in, I'm rerouted back to the root_path and the "Sign In" link still appears.

Edit: Here is the log output when I click Sign In:

Started POST "/users/sign_in" for ::1 at 2015-07-06 23:20:15 -0400
Processing by Devise::SessionsController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"6Eh4Qw3qErGmsppatErFZYhTOZHs8DhCOMXqGAMrBzRdTd72L5rIGAChLDvnI/GzOv1kQsyL43o/B6AQQtnk4Q==", "user"=>{"email"=>"broy@bullhorn.com", "password"=>"[FILTERED]", "remember_me"=>"0"}, "commit"=>"Log in"}
  User Load (0.2ms)  SELECT  "users".* FROM "users" WHERE "users"."email" = ?  ORDER BY "users"."id" ASC LIMIT 1  [["email", "b@gmail.com"]]
   (0.1ms)  begin transaction
  SQL (0.3ms)  UPDATE "users" SET "last_sign_in_at" = ?, "current_sign_in_at" = ?, "sign_in_count" = ?, "updated_at" = ? WHERE "users"."id" = ?  [["last_sign_in_at", "2015-07-07 03:17:08.826634"], ["current_sign_in_at", "2015-07-07 03:20:15.963289"], ["sign_in_count", 93], ["updated_at", "2015-07-07 03:20:15.964239"], ["id", 4]]
   (1.5ms)  commit transaction
Redirected to http://localhost:3000/
Completed 302 Found in 73ms (ActiveRecord: 2.1ms)


Started GET "/" for ::1 at 2015-07-06 23:20:15 -0400
Processing by ProductlinesController#index as HTML
  Productline Load (0.1ms)  SELECT "productlines".* FROM "productlines"
  Rendered productlines/index.html.erb within layouts/application (2.1ms)
  Rendered layouts/_header.html.erb (1.7ms)
Completed 200 OK in 48ms (Views: 47.3ms | ActiveRecord: 0.1ms)


Started GET "/" for ::1 at 2015-07-06 23:20:16 -0400
Processing by ProductlinesController#index as HTML
  Productline Load (0.2ms)  SELECT "productlines".* FROM "productlines"
  Rendered productlines/index.html.erb within layouts/application (104.8ms)
  Rendered layouts/_header.html.erb (1.1ms)
Completed 200 OK in 155ms (Views: 154.1ms | ActiveRecord: 0.2ms)

Do you want to put an exception in first on your authenticate user? That way it is not trying to run an authentication before current_user/@user/etc has even been set. For example if your root is index:

before_action :authenticate_user!, :except => [:index]

Then - be sure to have the better_errors gem and throw in some nonsense jibberish in your if user_signed_in? statement, refresh the page to trigger the console in the browser. See if @user or current_user or what you are using got set at all in the first place. I would then debug backwards from there.

https://github.com/charliesome/better_errors

Finally here is a stackoverflow link I came upon with a similar issue and a few answers below:

Rails devise: user_signed_in? not working

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM