Skip to main content

Rails 5.1.5 ( redirect to login but not saving data [omniauth + Devise]

Rails • Asked by Michael Lazuardy
Im Trying to make Oauth using multi model, User and Identity. 
i setup the one to many Relationship between User and Identity and write some code for each model like this
user.rb
class User < ApplicationRecord

  has_many :articles
  has_many :identities
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable, :omniauthable

  validates_presence_of :name

  def facebook
    identities.where( :provider => "facebook").first
  end
  
  def facebook_client
    @facebook_client ||= Facebook.client(access_token: facebook.accesstoken)
  end

end

identity.rb

class User < ApplicationRecord

  has_many :articles
  has_many :identities
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable, :omniauthable

  validates_presence_of :name

  def facebook
    identities.where( :provider => "facebook").first
  end
  
  def facebook_client
    @facebook_client ||= Facebook.client(access_token: facebook.accesstoken)
  end

end

making omniauth_callback in controllers/users/omniauth_callbacks_controller

class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
    def facebook
        generic_callback('facebook')
    end

    def generic_callback(provider)
        @identity = Identity.find_for_oauth env["omniauth.auth"]
        @user = @identity.user || User.find_by(email: @identity.email) || current_user
        if @user.nil?
            @user = User.create(email: @identity.email || "")
            @identity.update_attribute(:user_id, @user.id)
        end

        if @user.email.blank? && @identity.email
            @user.update_attribute(:email, @identity.email)
        end

        if @user.persisted?
            @identity.update_attribute(:user_id , @user.id)
            @user = User.find @user.id
            sign_in_and_redirect @user,event: :authentication
        else
            session["devise.#{provider}_data"] = env["omniauth.auth"]
            redirect_to new_user_registration_url
        end
    end
      def upgrade
    scope = nil
    if params[:provider] == "google_oauth2"
      scope = "email,profile,offline,https://www.googleapis.com/auth/admin.directory.user"
    end

    redirect_to user_omniauth_authorize_path( params[:provider] ), flash: { scope: scope }
  end

  def setup
    request.env['omniauth.strategy'].options['scope'] = flash[:scope] || request.env['omniauth.strategy'].options['scope']
    render :text => "Setup complete.", :status => 404
  end
end

and everything i set up correctly, until i hit the button for login with facebook, it return to my login page again but not save the session and also not save the data too like uid and provider. what's wrong with my code ? im new in ruby on rails. please help me and sorry my bad english

Ok so a few things spring to mind:
  1. Have you migrated the additional columns to your user model?  e.g. 'provider', 'uid'?
  2. Have you also added your app details in config/initializers/devise.rb?
    1. config.omniauth :facebook, ENV['FACEBOOK_APP_ID'], ENV['FACEBOOK_APP_SECRET'], scope: "email", info_fields: 'email, first_name, last_name'

no sir, i use Relationship between User and Identity, and the Identity will handle the user provider and uid,
already set up my devise.rb and env too

Login or Create An Account to join the conversation.

Subscribe to the newsletter

Join 24,647+ developers who get early access to new screencasts, articles, guides, updates, and more.

    By clicking this button, you agree to the GoRails Terms of Service and Privacy Policy.

    More of a social being? We're also on Twitter and YouTube.