簡體   English   中英

設計:登錄后 current_user 為 nil

[英]Devise: current_user is nil after sign in

我在使用 Devise 時遇到了一個非常令人困惑的問題,我能夠成功登錄,但之后似乎立即注銷了。 在 sessions#create 操作中放置斷點我可以看到 current_user 設置准確,但是,一旦 sessions#create 重定向到另一個控制器,current_user 為 nil。 什么會導致這種行為?

會話控制器:

class SessionsController < Devise::SessionsController
  def create
    respond_to do |format|
      format.html do
        self.resource = warden.authenticate!(auth_options)
        sign_in(resource_name, resource)
        # at this point current_user is set appropriately
        redirect_to users_path
      end
    end
  end

  def destroy
    signed_out = (Devise.sign_out_all_scopes ? sign_out : sign_out(resource_name))

    respond_to do |format|
      format.html do
        redirect_to :destroy_session_path
      end
      format.json do
        render status: 201
      end
    end
  end
end

用戶控制器:

class UsersController < ActionController::Base

  layout 'layouts/application'

  def index
     # current_user is nil here
  end
end

路線:

Rails.application.routes.draw do
  devise_for :users, controllers: { sessions: 'sessions' }

  devise_scope :user do
    scope '/admin' do
      resources :users
    end
  end
end

我看到了完全相同的問題。 有什么解決辦法嗎?

我的調試輸出:

使用 devise 成功登錄后是會話控制器創建方法的調試:

[2021-05-14 09:42:15] INFO -- ======================= SessionsController: User deviseuser@somesite.com signed-in from Web browser.

其次是:

[2021-05-14 10:16:03] INFO -- Completed 302 Found in 102ms (ActiveRecord: 0.0ms)
[2021-05-14 10:16:03] INFO -- Started GET "/" for 12.23.34.56 at 2021-05-14 09:42:15 -0700
[2021-05-14 10:16:03] INFO -- Processing by RuntimeController#index as HTML

[2021-05-14 10:16:03] DEBUG -- Warden::Manager.after_failed_fetch: User nil   opts: {:scope=>:user}
[2021-05-14 10:16:03] DEBUG -- authenticate_user!:  before 'super' user_signed_in? = false   current_user = nil
[2021-05-14 10:16:03] INFO -- Completed 401 Unauthorized in 1ms (ActiveRecord: 0.0ms)
[2021-05-14 10:16:03] INFO -- Warden::Manager: before_failure  opts: {:scope=>:user, :action=>"unauthenticated", :message=>nil, :attempted_path=>"/"}.

因此在成功登錄后 after_sign_in_path_for 正確返回重定向的根“/”路徑。
RuntimeController 通過 routes.rb 被正確識別為路由路徑的處理程序。 然而,事情在這一點上變壞了。 正如 OP 指出的那樣, current_user 在成功登錄后以某種方式重置為 nil 。

根據 Warden 內聯評論,方法 Warden::Manager.after_failed_fetch 是

# A callback that runs if no user could be fetched, meaning there is now no user logged in.

這會導致Completed 401 Unauthorized輸出。

還要注意mysql數據庫中的User記錄與signed_in = 1一致,其他字段設置適當。

我應該指出這段代碼多年來一直正常工作。 顯然有一個更新破壞了系統:即不再兼容的 ruby、rails 或 gem。 但是,我看不出區別在哪里。

RoR配置

$ rails -v
Rails 5.0.1
$ ruby -v
ruby 2.3.3p222 (2016-11-21 revision 56859) [x86_64-linux]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM