Search code examples
ruby-on-railsdeviseopenidomniauthgoogle-openid

Devise Omniauth with google open-id access token information


I'm new in rails and I'm trying to integrate omniauth and the login with google. Surfing on the web i found a way to do it, but i got this error:

undefined method `[]' for nil:NilClass

app/models/user.rb:22:in `find_for_open_id'
app/controllers/users/omniauth_callbacks_controller.rb:17:in `open_id'

I think that is because i don't access correctly the access token information.

here is the code:

Model users.rb

def self.find_for_open_id(access_token, signed_in_resource=nil)    
    data = access_token['user_info']
    if user = User.find_by_email(data["email"])
    user
    else # Create a user with a stub password.
      User.create!(:email => data["email"], :password => Devise.friendly_token[0,20])
    end
  end

omniauth_callbacks_controller.rb

def open_id
    # You need to implement the method below in your model
    @user = User.find_for_open_id(env["omniauth.auth"], current_user)
    if @user.persisted?
      flash[:notice] = I18n.t "devise.omniauth_callbacks.success", :kind => "Google"
      sign_in_and_redirect @user, :event => :authentication
    else
      session["devise.open:id_data"] = env["openid.ext1"]
      redirect_to new_user_registration_url
    end
  end

devise.rb

config.omniauth :open_id, :store => OpenID::Store::Filesystem.new("/tmp"), :name => 'open_id', :identifier => 'https://www.google.com/accounts/o8/id'

I don't know what else i can show you.

For me the problem is here:

data = access_token['user_info']

access_token['user_info'] returns null.

Am I doing something wrong? Is there other way to access the 'user_info' and then the e-mail?

Thanks in advance. Hope i'm clear.


Solution

  • You should just be using data = access_token['info'] instead of data = access_token['user_info']

    From there you have access to data['email], data['first_name'], and data['last_name'].