user.rb

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28

 def password_required?
   (authentications.empty? || !password.blank?) && super
 end

 def apply_omniauth(omniauth)
   case omniauth['provider']
   when 'facebook'
     self.apply_facebook(omniauth)
   end
   authentications.build(:provider => omniauth['provider'], :uid => omniauth['uid'], :token =>(omniauth['credentials']['token'] rescue nil))
 end

 def facebook
   @fb_user ||= FbGraph::User.me(self.authentications.find_by_provider('facebook').token)
 end


 protected

 def apply_facebook(omniauth)                    
   if (extra = omniauth['extra']['user_hash'] rescue false)       # <--- this method gives error
     self.email = (extra['email'] rescue '')
   end
 end

end

authentications controller

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
class AuthenticationsController < ApplicationController
  def index
    @title = "Authentications"
    @authentications = current_user.authentications if current_user
  end

  def create
   omniauth = request.env["omniauth.auth"]
   authentication = Authentication.find_by_provider_and_uid(omniauth['provider'], omniauth['uid'])
   if authentication
     flash[:notice] = "Signed in successfully"
     sign_in_and_redirect(:user, authentication.user)
   elsif current_user
     current_user.authentications.create(:provider => omniauth['provider'], :uid => omniauth['uid'])
     flash[:notice] = "authentications successful"
     redirect_to authentications_url
   else
     user = User.new
     user.apply_omniauth(omniauth)
     if user.save
       flash[:notice] = "Signed in successfully"
       sign_in_and_redirect(:user, root_path)
     else
       session[:omniauth] = omniauth
       redirect_to new_user_registration_url
   end
  end
end

  def destroy
    @authentication = current_user.authentications.find(params[:id])
    @authentication.destroy
    flash[:notice] = "Successfully destroyed authentication."
    redirect_to authentications_url
  end
end

registrations controller

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class RegistrationsController < Devise::RegistrationsController
  def create
      super
      session[:omniauth] = nil unless @user.new_record?
    end



  def destroy
    resource.destroy 
    set_flash_message :notice, :destroyed
    sign_out_and_redirect(self.resource)
  end

  private

  def build_resource(*args)
    super
    if session[:omniauth]
      @user.apply_omniauth(session[:omniauth])
      @user.valid?
    end
  end



end