jeudi 6 août 2015

Omniauth and google oauth2 error without Devise - Rails 4

Hey guys so i am trying to implement social authentications but i am stuck.

I've setup correctly the callback url both in my routes and google console and i've verified it by displaying the auth_hash in browser.

my session_controller.rb

def google_oauth2
    begin
    auth_hash = request.env['omniauth.auth']
    @user = User.from_omniauth(auth_hash)
    if @user
      session[:user_id] = @user.id
      flash[:success] = "Welcome, #{@user.name}!"
      redirect_to root_path
    else
      user.uid = auth_hash['uid']
      user.provider = auth_hash['provider']
      user.name = auth_hash['info']['name']
      user.email = auth_hash['info']['email']
      user.image_url = auth_hash['info']['image']

      @user = User.new(name: user.name,email: user.email, provider: user.provider,uid: user.uid,image_url: image_url)
      @user.save!
      flash[:success] = "Welcome, #{@user.name}!You've signed up!"
    end
    rescue
      flash[:warning] = "There was an error while trying to authenticate you..."
    end
    redirect_to root_path
  end

user.model

def self.from_omniauth(auth_hash)
      user = find_by(uid: auth_hash['uid'], provider: auth_hash['provider'])
      user
end

And this is the error in console

Started GET "/auth/google_oauth2/callback?state=a85d28b3b8d112171450ab3cafd47216937847a5747c08f4&code=4/H37yKnP8xbG_d2DEwS55WyAUXTlhBRlliREvGzZhD9s" for ::1 at 2015-08-06 19:13:02 +0300
I, [2015-08-06T19:13:02.114803 #5401]  INFO -- omniauth: (google_oauth2) Callback phase initiated.
Processing by SessionsController#google_oauth2 as HTML
  Parameters: {"state"=>"a85d28b3b8d112171450ab3cafd47216937847a5747c08f4", "code"=>"4/H37yKnP8xbG_d2DEwS55WyAUXTlhBRlliREvGzZhD9s", "provider"=>"google_oauth2"}
  User Load (0.1ms)  SELECT  "users".* FROM "users" WHERE "users"."uid" = ? AND "users"."provider" = ? LIMIT 1  [["uid", "118084345864130537689"], ["provider", "google_oauth2"]]
Redirected to http://localhost:3000/
Completed 302 Found in 9ms (ActiveRecord: 0.6ms)

The problem is that the error in my session controller fires each time,and no user is created

"There was an error while trying to authenticate you..."

Anyone who can collaborate?

Aucun commentaire:

Enregistrer un commentaire