Login to VS register | reinvent with omniauth-facebook

  • Rails 5.0.0.1
  • Ruby 2.3.1p112
  • gem 'devise'
  • gem 'omniauth'
  • gem 'omniauth-facebook'

I have an application that works with omniauth-facebook and Devise, which should have some required additional attributes on the registration page. It works very well, but I am having difficulty with authentication violation in two situations / behavior:

  • A specific page for the user is registered, requiring additional parameters.
  • A specific page for user login (if the user has already registered).

The problem is the first_or_create method.

I need to create an entry only on the registration page with my required parameters, otherwise on the login page I just need to check if the user has already registered and redirects to register the page if necessary.

Am i clear

Model:

class User < ActiveRecord::Base
    def self.from_omniauth(auth)
        where(provider: auth.provider, uid: auth.uid).first_or_create do |user|
            user.email = auth.info.email
            user.password = Devise.friendly_token[0,20]
            user.name = auth.info.name
            user.avatar = auth.info.picture
            user.username = auth.info.name.parameterize.dasherize.first(10) + Digest::SHA2.hexdigest("#{Time.now.utc}").first(5)
            user.skip_confirmation!
        end
    end
end

Callback:

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

        params = request.env["omniauth.params"]
        @user.username = params["username"]
        @user.newsletter = params["newsletter"]
        @user.diet_id = params["diet_id"]

        if @user.persisted?
            sign_in_and_redirect @user, event: :authentication
            set_flash_message(:notice, :success, kind: "Facebook") if is_navigational_format?
        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 corresponding code for the registration page:

= form_tag user_facebook_omniauth_authorize_path(newsletter: @user.newsletter, username: @user.username, diet_id: @user.diet_id) do

Corresponding code for the login page:

= link_to "Sign in with Facebook", user_facebook_omniauth_authorize_path 
+4
source share

Source: https://habr.com/ru/post/1657626/


All Articles