Josemafuen
Josemafuen

Reputation: 642

Google Authentication error Ruby on Rails

I'm trying to implement Google authentication on my Rails app but I'm having some trouble.

Following https://richonrails.com/articles/google-authentication-in-ruby-on-rails/, I created my initializer with the keys I got from Google's developer console 'omniauth.rb'

OmniAuth.config.logger = Rails.logger

Rails.application.config.middleware.use OmniAuth::Builder do
  provider :google_oauth2, '*****', '*****', {client_options: {ssl: {ca_file: Rails.root.join("cacert.pem").to_s}}}
end

I added some routes

  # GOOGLE AUTH
  get 'auth/:provider/callback', to: 'sessions#create'
  get 'auth/failure', to: redirect('/')
  get 'signout', to: 'sessions#destroy', as: 'signout'

My sessions' create action

def create
    user = User.from_omniauth(env["omniauth.auth"])
    sign_in user
    flash[:success] = 'Logged in!'
    redirect_to root_path
end

And the User.from_omniauth method in user's model

def self.from_omniauth(auth)
    where(provider: auth.provider, uid: auth.uid).first_or_initialize.tap do |user|
      user.password = user.password_confirmation = user.password_digest =  SecureRandom.urlsafe_base64(n=6)
      user.provider = auth.provider
      user.uid = auth.uid
      user.name = auth.info.name
      user.oauth_token = auth.credentials.token
      user.oauth_expires_at = Time.at(auth.credentials.expires_at)
      user.save!
    end
  end

I set a random password because I'm using also bcrypt authentication and it forces that every user has one password

Lastly, in my view I have a button for login

= link_to "Sign in with Google", "/auth/google_oauth2", id: "sign_in", class: "btn btn-primary"

The problem is that it doesn't work, when I click it an error shows on sessions' create user = User.from_omniauth(env["omniauth.auth"]):

NameError at /auth/google_oauth2/callback
undefined local variable or method `env' for #<SessionsController:0x956eb90>

Other times it throws SSL_connect SYSCALL returned=5 errno=0 state=SSLv2/v3 read server hello A (OpenSSL::SSL::SSLError) in another line but I guess that's a different mistake.

Upvotes: 1

Views: 922

Answers (1)

Aakash Gupta
Aakash Gupta

Reputation: 756

There is no env method available. Instead of this, use

user = User.from_omniauth(request.env["omniauth.auth"])

in your create method as request.env["omniauth.auth"] object has the information sent by google after authentication of user to your application.

Upvotes: 4

Related Questions