2

I can't get devise omniauth-facebook to work. I've followed the devise guide to no avail. I think my problem is the model is not retrieving info.

Model

class User < ActiveRecord::Base
  has_attached_file :image, styles: {large: "1920x1080#", medium:              "800x500#", thumb: "100x100"}, :default_url =>    "/images/:style/missing.png"
  validates_attachment_content_type :image, :content_type =>    ["image/jpg", "image/jpeg", "image/png", "image/gif"]

  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
     :recoverable, :rememberable, :trackable, :validatable,
     :omniauthable, :omniauth_providers => [:facebook]
  def admin?
    admin
  end

  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   # assuming the user model has a     name
      user.image = auth.info.image # assuming the user model has an image
      puts request.env["omniauth.auth"]
    end
  end

  def self.new_with_session(params, session)
    super.tap do |user|
      if data = session["devise.facebook_data"] &&     session["devise.facebook_data"]["extra"]["raw_info"]
        user.email = data["email"] if user.email.blank?
      end
    end
  end
end

Routes.rb

Rails.application.routes.draw do

  mount RailsAdmin::Engine => '/admin', as: 'rails_admin'

  devise_for :users do
    delete 'logout' => 'sessions#destroy', :as => :destroy_user_session,
    :controllers => { :omniauth_callbacks => "user/omniauth_callbacks" }
  end

Controller

class User::OmniauthCallbacksController <         Devise::OmniauthCallbacksController
  # You should configure your model like this:
  # devise :omniauthable, omniauth_providers: [:twitter]

  # You should also create an action method in this controller like this:
  # def twitter
  # end
  def facebook
    # You need to implement the method below in your model (e.g. app/models/user.rb)
    @user = User.from_omniauth(request.env["omniauth.auth"])
    if @user.persisted?
      sign_in_and_redirect @user, :event => :authentication #this will throw if @user is not activated
      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 self.new_with_session(params, session)
    if session["devise.user_attributes"]
      new(session[devise.user_attributes], without_protection: true) do |user|
        user.attributes = params
        user.valid?
      end
    else
      super
    end

After I click "Login with facebook", it directs to a facebook url, I input a password, press enter, get redirected to the same page with a long url. (http://localhost:3000/demographics?code=AQDK1z40APoLiWykomxDDUljBUNHotenM4lzj_bZMhH8iQ74J_Nu_EUnPqBqkbNAeWQEPZwQs7YghqkB4eD7AoQLkN_RuYIlmotMtrJc4UyGRSe3CJIHcxp6kcB9BuYHA_Ldz0NMJvvGzOuvC-uDpFn6TyrzvV5v9LvivORXVduSsCy7_r6PcW8jxAkWqZzKyASXf26h8h3f_kha2d0KX6Ygft8ozN1HT9Xr-1y7ZtIKgTXEGMrqK950kASv2oTE0tQ5CYt6mfEZsVyLpykYIApOls8NLhjOaOIJewzV9EnLdSq0FbrvtedhhDmy-hg6IkRAbRVgwEkfUFsi9DXoxKyX&state=bdbf498f33f67ef57f3f54b846f870f21bb80c039c099f1a#=)

EDIT:

Now I am getting

Could not authenticate you from Facebook because "Invalid credentials".
Brian Lau
  • 127
  • 14
  • I don't know how to log errors. I putting binding.pry in the controller, model, but it doesn't get triggered. However, in my omniauth_callbacks.rb, I changed class User to class Users and that fixed a problem. Any chance you can help me figure out how to debug? – Brian Lau Feb 26 '16 at 20:47
  • Have you configured your `initializers/devise.rb` with your facebook key and secret credentials? – Federico Feb 29 '16 at 16:52
  • Yes, I hardcoded in there. The APPID and APPSECRET – Brian Lau Feb 29 '16 at 19:54

3 Answers3

0

This is what worked for me:

user model

devise :omniauthable, :omniauth_providers => [:facebook]

def self.from_omniauth(auth)
  where(provider: auth.provider, uid: auth.uid).first_or_create do |user|
      user.provider = auth.provider
      user.uid = auth.uid
      user.email = auth.info.email
      user.username = auth.info.name #gives full user name
      user.password = Devise.friendly_token[0,20]
      user.skip_confirmation!
      user.save
    end
end

devise.rb

config.omniauth :facebook, ENV['facebook_key'], ENV['facebook_secret'],
 scope: 'email,public_profile', info_fields: 'email, first_name, last_name'

callbacks_controller.rb

class CallbacksController < ApplicationController
  def facebook
    @user = User.from_omniauth(request.env["omniauth.auth"])
    if @user.persisted?
      sign_in_and_redirect @user, :event => :authentication
      flash[:notice] = "Logged in as #{@user.username}"      
    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

routes.rb

devise_for :users, controllers: { omniauth_callbacks: "callbacks" }
kirqe
  • 2,431
  • 4
  • 37
  • 63
0

So the problem was I didn't config the routes properly.

In fact, I had to remove all existing devise routes and add this line.

devise_for :users, :controllers => { :omniauth_callbacks => "users/omniauth_callbacks" }
Brian Lau
  • 127
  • 14
0

The problem is Facebook is not always returning email for user

from facebook developers https://developers.facebook.com/bugs/298946933534016

Some possible reasons:

  • No Email address on account
  • No confirmed email address on account
  • No verified email address on account
  • User entered a security checkpoint which required them to reconfirm their email address and they have not yet done so
  • Users's email address is unreachable

Set an condition in your controller if request.env["omniauth.auth"].info.email.present? see the script below.

    class User::OmniauthCallbacksController < Devise::OmniauthCallbacksController
      def facebook
        puts request.env["omniauth.auth"]   #  check if request.env["omniauth.auth"] is provided an email
        if request.env["omniauth.auth"].info.email.present?
            @user = User.from_omniauth(request.env["omniauth.auth"])
            if @user.persisted?
              sign_in_and_redirect @user, :event => :authentication #this will throw if @user is not activated
              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
        else
            redirect_to new_user_registration_url, notice: "Couldn't connect to your #{request.env["omniauth.auth"].provider} account. Try to sign up."
        end    
      end
    end
Marcelo Austria
  • 861
  • 8
  • 16