简体   繁体   中英

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

I'm using Rails 6 + Devise for login/registration. Users can register/login with Facebook via omniauth.

I want to log one analytics event when the user logs in, and a different analytics event when they register for the first time.

app/controllers/users/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

The flash[:log_event] is passed to Google Analytics. My problem is that Devise seems to follow the same code path for first registration as it does for a regular login.

I suppose I could check the @user.created_at timestamp, and treat it as a registration if it's a couple of minutes old, but I'm sure there's a cleaner solution.

You can always make your own version of User.from_omniauth . Notice the first_or_initialize instead of ..._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

Then in your controller check for 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?
# ....

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