[英]Create password for user logging into Rails app using Omniauth and Devise
[英]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.