Trying to get Cucumber working with OmniAuth - ruby-on-rails

I have been pulling my hair out because of this.
My cucumber step clicks on a login for facebook. I have mocked omniauth by following the following article:
http://pivotallabs.com/users/mgehard/blog/articles/1595-testing-omniauth-based-login-via-cucumber
My omniauth_callbacks_controller.rb has the following code:
class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
def my_logger
##my_logger = Logger.new("#{Rails.root}/log/my.log")
end
def facebook
#user = User.find_for_facebook_oauth(env["omniauth.auth"], current_user)
if #user.persisted?
flash[:notice] = I18n.t "devise.omniauth_callbacks.success", :kind => "Facebook"
sign_in_and_redirect #user, :event => :authentication
else
session["devise.facebook_data"] = env["omniauth.auth"]
redirect_to new_user_registration_url
end
end
end
I however, get the following error:
When I follow "facebook_login_button" # features/step_definitions/basic.rb:14
undefined method `extra' for #<Hash:0x007fda6d7cd950> (NoMethodError)
./app/models/user.rb:13:in `find_for_facebook_oauth'
./app/controllers/users/omniauth_callbacks_controller.rb:8:in `facebook'
(eval):2:in `click_link'
./features/step_definitions/basic.rb:15:in `/^(?:|I )follow "([^"]*)"$/'
features/homepage.feature:30:in `When I follow "facebook_login_button"'
Other articles I have read:
Devise 1.5 + Omniauth 1.0 + Facebook: undefined method `extra` - problem: this is mocking out omniauth using rspec I think - not sure if it can be applied for cucumber
https://github.com/intridea/omniauth/issues/558 --post by benjamintanweihao works - but its hacking the code to work differently with tests - the git branches suggested dont work either
EDIT: my model/user.rb
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :token_authenticatable, :lockable, :timeoutable, :confirmable and :activatable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
devise :omniauthable
# Setup accessible (or protected) attributes for your model
attr_accessible :email, :password, :password_confirmation, :remember_me
def self.find_for_facebook_oauth(access_token, signed_in_resource=nil)
data = access_token.extra.raw_info
if user = User.where(:email => data.email).first
user
else
User.create!(:email => data.email, :password => Devise.friendly_token[0,20])
end
end
end

This hapens due do this issue: https://github.com/intridea/omniauth/issues/558
It is not your fault, it is a small bug in omniauth.
you can use methods like access_token.extra in production and development mode, but in order to make it work in test mode you should change it to access_token["extra"]

Related

Ominauth: Google_oauth2 error in rails devise email confirmation issues (You have to confirm your email address before continuing.)

I'm trying use the google login oauth2 in my project, all the codes successfully fixed in right position but I dont want the google oauth2 features to request for email verification just straight to login, I prefer it to get skipped, how do I achieve this without removing the :confirmable devise module? this is my code user.rb in model
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable,
:confirmable, :omniauthable, omniauth_providers: [:github, :google_oauth2]
has_many :friends
def self.from_omniauth(access_token)
data = access_token.info
user = User.where(email: data['email']).first
unless user
user = User.create(
email: data['email'],
password: Devise.friendly_token[0,20]
)
end
user
end
end
This is code for the omniauth callback controller .rb
class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
def google_oauth2
handle_auth "Google"
end
def github
handle_auth "Github"
end
def handle_auth(kind)
# You need to implement the method below in your model (e.g. app/models/user.rb)
#user = User.from_omniauth(request.env['omniauth.auth'])
if #user.persisted?
flash[:notice] = I18n.t 'devise.omniauth_callbacks.success', kind: kind
sign_in_and_redirect #user, event: :authentication
else
session['devise.auth_data'] = request.env['omniauth.auth'].except('extra') # Removing extra as it can overflow some session stores
redirect_to new_user_registration_url, alert: #user.errors.full_messages.join("\n")
end
end
end
The Devise Confirmable Module provides a skip_confirmation! method to do this. In your from_omniauth function, instead of
user = User.create(
email: data['email'],
password: Devise.friendly_token[0,20]
)
Instead do this
user = User.new(
email: data['email'],
password: Devise.friendly_token[0,20]
)
user.skip_confirmation!
user.save!

ActionController::RoutingError (uninitialized constant Users::OmniauthCallbacksController) Devise and google_oauth2

I have followed the tutorial from this link and keep ending up with the following log messages:
Started GET "/users/auth/google_oauth2" for 127.0.0.1 at 2019-02-22 20:59:25 +1100
I, [2019-02-22T20:59:25.512091 #11001] INFO -- omniauth: (google_oauth2) Request phase initiated.
Started GET "/users/auth/google_oauth2/callback?state=...
I, [2019-02-22T20:59:29.060352 #11001] INFO -- omniauth: (google_oauth2) Callback phase initiated.
ActionController::RoutingError (uninitialized constant Users::OmniauthCallbacksController):
I've searched online and all the solutions suggest checking the spelling in various files. I've included them below.
Devise _links.html.erb:
<%- if devise_mapping.omniauthable? %>
<%- resource_class.omniauth_providers.each do |provider| %>
<%= link_to "Sign in with #{OmniAuth::Utils.camelize(provider)}", user_google_oauth2_omniauth_authorize_path %><br />
<% end -%>
<% end -%>
devise.rb:
config.omniauth :google_oauth2, client_id, client_secret, {
scope: "contacts.readonly,userinfo.email,userinfo.profile,youtube",
prompt: 'select_account',
image_aspect_ratio: 'square',
image_size: 50
}
User.rb:
class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable, :omniauthable, :omniauth_providers => [:google_oauth2]
def self.from_omniauth(auth)
where(provider: auth.provider, uid: auth.uid).first_or_create do |user|
user.token = auth.credentials.token
user.expires = auth.credentials.expires
user.expires_at = auth.credentials.expires_at
user.refresh_token = auth.credentials.refresh_token
end
end
end
/app/controllers/users/omniauth_callbacks_controllers.rb
class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
def google_oauth2
#user = User.from_omniauth(request.env["omniauth.auth"])
if #user.persisted?
sign_in #user, :event => :authentication #this will throw if #user is not activated
set_flash_message(:notice, :success, :kind => "Google") if is_navigational_format?
else
session["devise.google_data"] = request.env["omniauth.auth"]
end
redirect_to '/'
end
end
routes.rb
devise_for :users, controllers: {omniauth_callbacks: "users/omniauth_callbacks"}
google console
I have set up my google console with the following Authorised redirect URLs:
http://localhost:3000/users/auth/google_oauth2/callback
Rails Routes
When I do a rails routes I have:
user_google_oauth2_omniauth_authorize GET|POST /users/auth/google_oauth2(.:format) users/omniauth_callbacks#passthru
user_google_oauth2_omniauth_callback GET|POST /users/auth/google_oauth2/callback(.:format) users/omniauth_callbacks#google_oauth2
Any assistance to know why this isn't working would be greatly appreciated.
/app/controllers/users/omniauth_callbacks_controllers.rb
This is not correct. You have an additional s in your controller name. This is why rails does not manage to find the class. You should rename your controller name to omniauth_callbacks_controller.rb.

Devise Google oauth authentication failure

I started getting this error after updating my rails app and all the gems to the most current versions and cant figure out whats causing it:
ERROR -- omniauth: (google_oauth2) Authentication failure! csrf_detected: OmniAuth::Strategies::OAuth2::CallbackError, csrf_detected | CSRF detected
First heres the initializer in devise.rb:
config.omniauth :google_oauth2, ENV['GOOGLE_CLIENT_ID'], ENV['GOOGLE_CLIENT_SECRET'],
{ access_type: 'offline',
prompt: 'consent',
select_account: true,
scope: 'userinfo.email,userinfo.profile',
client_options: {ssl: {ca_file: Rails.root.join("cacert.pem").to_s}}
}
User.rb has this:
class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable, :confirmable,
:recoverable, :rememberable, :trackable, :validatable,
:omniauthable, omniauth_providers: [:google_oauth2, :facebook]
def self.from_omniauth(auth)
identity = Identity.find_for_oauth(auth)
if identity.nil?
identity = Identity.create_with_oauth(auth)
end
if identity.user.present?
return identity.user
else
registered_user = User.find_or_create_by(email: auth[:info][:email])
if registered_user && auth[:provider] == "google_oauth2"
registered_user.firstname = auth[:info][:first_name] if registered_user.firstname.blank?
registered_user.lastname = auth[:info][:last_name] if registered_user.lastname.blank?
registered_user.displayname = auth[:info][:name] if registered_user.displayname.blank?
registered_user.avatar_remote_url = auth[:info][:image] if registered_user.avatar_data.blank?
identity.user = registered_user
identity.save
registered_user.skip_confirmation!
registered_user.avatar_remote_url = auth[:info][:image]
registered_user.save
return registered_user
end
end
end
The Callback controller
class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
# You should configure your model like this:
# devise :omniauthable, omniauth_providers: [:twitter]
# You should also create an action method in this controller like this:
def google_oauth2
#user = User.from_omniauth(request.env["omniauth.auth"])
if #user
sign_in #user
redirect_to root_path
else
redirect_to new_user_session_path, notice: 'Access Denied.'
end
end
Ive tried searching for an answer but nothing fits the same and has worked

Spotify Omniauth

I'm trying to do OmniAuth in rails 4 for spotify. I almost have it but for some reason, the redirect URI isn't working. I am using Devise with omniauth These are my files:
User.rb
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable,
:omniauthable, :omniauth_providers => [:spotify]
def self.from_omniauth(auth)
where(provider: auth.provider, uid: auth.uid).first_or_create do |user|
user.provider = auth.provider
user.uid = auth.uid
user.email = auth.info.email
user.password = Devise.friendly_token[0,20]
end
end
end
My Callbacks controller to handle callbacks
class CallbacksController < Devise::OmniauthCallbacksController
def spotify
#user = User.from_omniauth(request.env["omniauth.auth"])
sign_in_and_redirect #user
end
end
My Devise.rb snippet:
config.omniauth :spotify, client_id, client_secret,scope: 'playlist-read-private user-read-private user-read-email'
My Routes.rb
Rails.application.routes.draw do
devise_for :users, :controllers => { :omniauth_callbacks => 'callbacks' }
get '/users/auth/callback', to: 'callbacks#spotify'
end
And lastly, the link leading up to the login:
<%= link_to 'Sign in with Spotify', user_omniauth_authorize_path(:spotify) %>
But for some reason, whenever I try to log into spotify, it says invalid redirect URI
OK, I figured out a solution to my particular problem:
When it was giving me the error of "invalid redirect URI", I looked at the URI it was trying to go to and I simply used that.
Then I got a second error which gave me a SSL Cert error so I used "gem certified" to fix that. THEN, it gave me a third problem of unauthorized access (the callback returned a failed request). What was happening was that I was trying to use OmniAuth twice. I had two files:
A) OmniAuth.rb
and B) Devise.rb
Both of these files were making API calls and it was messing it up. So to anyone having this problem- don't use both omniauth and devise. Honestly, after the first initial hiccup, I found devise to be way more useful than making your own User model and applying omniauth to that. Devise is more comprehensive!

Rails: Omniauth & Devise. Getting a nil object unexpectedly

I followed Railscasts(ASCII versions) #235 and and part of #236 to setup creating user authentications using OmniAuth & Devise: OmniAuth Part 1 OmniAuth Part 2
I am at the stage where I just modified the create method of the authentications controller to allow user's not signed in to the site to sign in directly via twitter. The code for the create method is as follows:
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."
logger.info("AUTHENTICATION: #{authentication.inspect}")
#logger.info("AUTHENTICATION METHODS: #{authentication.methods.sort}")
logger.info("authentication.user: #{authentication.user}")
#logger.info("authentication.user.nil?: #{authentication.user.nil?}")
#logger.info("authentication.user.id: #{authentication.user.id}")
sign_in_and_redirect(:user, authentication.user)
else
current_user.authentications.create(:provider => omniauth['provider'], :uid => omniauth['uid'])
flash[:notice] = "Authentication successful."
redirect_to authentications_url
end
end
Now when I go to /auth/twitter, I get this error:
No route matches "/auth/failure"
This is because authentication.user is nil. The code for the create method is exactly as per the Railscast, and I don't see why authentication.user is nil.
This is the output of the authentication.inspect:
#<Authentication id: 1, user_id: 1, provider: "twitter", uid: "319521616", created_at: "2011-08-01 10:32:48", updated_at: "2011-08-01 10:32:48">
Does anyone have any insight as to whyauthentication.user would be nil, even tough the inspect method returns valid data.
Here is the code from my user model:
class User < ActiveRecord::Base
has_many :authentications
# Include default devise modules. Others available are:
# :token_authenticatable, :encryptable, :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable,
:lockable, :confirmable #Added lockable and confirmable
# Setup accessible (or protected) attributes for your model
attr_accessible :email, :password, :password_confirmation, :remember_me
end
Do you have any validations in your user model? This caused a silent fail on saving the user model, for me, which led to the error message you describe, when I did the same set up. Just one idea.

Resources