Search code examples
ruby-on-rails-5omniauthgoogle-authenticationnomethoderror

NoMethodError (undefined method `info' for nil:NilClass) `find_for_google_oauth2'


! am trying to allow co-workers and students to sign up using their google project accounts. I have gotten as far as the token being passed but then i get an error.

  1. app/models/user.rb:70:in `find_for_google_oauth2'

app/controllers/authentications_controller.rb:5:in `create'

my authentication controller create method

    def create
       auth = request.env[":google_oauth2"]
       @user = User.find_for_google_oauth2(request.env["omniauth.auth"])
       redirect_to root_url, :notice => "Signed in!"
   end

my user model

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.first_name = auth.info.first_name
       user.last_name = auth.info.last_name   # assuming the user model has a name
       user.image = auth.info.image # assuming the user model has an image
  end
 end

    def self.find_for_google_oauth2(access_token, signed_in_resource=nil)
        data = access_token.info
        user = User.where(:email => data["email"]).first


    unless user
        user = User.create(name: data["name"],
             email: data["email"],
             uid: access_token.uid,
             provider: access_token.provider,
             password: Devise.friendly_token[0,20]
            )
          end
          user
        end

and my config/omniauth.rd

require 'omniauth-google-oauth2'

OmniAuth.config.logger = Rails.logger
  OmniAuth.logger.progname = "omniauth"
Rails.application.config.middleware.use OmniAuth::Builder do



    provider :google_oauth2, '***********petnk.apps.googleusercontent.com',
        google_client_secret: '***********',
        prompt: "consent",
        select_account: true,
        scope: 'userinfo.email',
        image_aspect_ratio: 'square',
        image_size: 50
        on_failure { |env|AuthenticationsController.action(:failure).call(env) }

    end

Not sure what to include to help y'all help me. I am new to rails and have been trying to learn for the past year so any help is appreciated.

thanks


Solution

  • I had to move my create function from my authentication controller to my omnicontroller. not really sure why this solved the problem but for now it did.