簡體   English   中英

我如何知道用戶何時注冊與在 Rails 中使用 Devise 和 Omniauth 登錄

[英]How do I know when a user is registering vs logging in with Devise and Omniauth in Rails

我正在使用 Rails 6 + Devise 進行登錄/注冊。 用戶可以通過omniauth注冊/登錄Facebook。

我想在用戶登錄時記錄一個分析事件,並在他們第一次注冊時記錄一個不同的分析事件。

應用程序/控制器/用戶/omniauth_callbacks_controller.rb

class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
  def facebook
    @user = User.from_omniauth(request.env["omniauth.auth"])

    if @user.persisted?
      sign_in_and_redirect @user, :event => :authentication
      set_flash_message(:notice, :success, :kind => "Facebook") if is_navigational_format?
      flash[:log_event] = {
        'event_category' => 'engagement',
        'event_name' => 'login',
        'method' => 'facebook'
      }
    else
      session["devise.facebook_data"] = request.env["omniauth.auth"]
      redirect_to new_user_registration_url
    end
  end

  def failure
    redirect_to root_path
  end

end

flash[:log_event]被傳遞給 Google Analytics。 我的問題是 Devise 似乎遵循與常規登錄相同的代碼路徑進行首次注冊。

我想我可以檢查@user.created_at時間戳,如果它是幾分鍾前的,則將其視為注冊,但我確信有一個更清潔的解決方案。

您始終可以制作自己的User.from_omniauth版本。 注意first_or_initialize而不是..._create

# in app/models/user.rb

def self.from_omniauth(auth)
  user = where(auth.slice(:provider, :uid)).first_or_initialize do |new_user|
    new_user.provider = auth.provider
    new_user.uid = auth.uid
    new_user.username = auth.info.nickname
  end
  user.image_url = auth.info.image # need to update in case image changed on provider's site
  user
end

然后在您的 controller 檢查new_record?

@user = User.from_omniauth(request.env["omniauth.auth"])

if @user.new_record?
  @user.save  # Important step I missed earlier
  # ... Do some custom thing here for your app
end

if @user.persisted?
# ....

暫無
暫無

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

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