I am trying to write tests for OmniAuth users and after setting up my test_helper, I am running into and a bad URI error.Sharing the details below:
test_helper.rb
# OmniAuth auth mock for testing
def setup_omniauth_mock (user)
OmniAuth.config.test_mode = true
OmniAuth::AuthHash.new ({
'provider' => 'google',
'uid' => '123545',
'user_id' => '2',
'first_name' => 'X',
'last_name' => 'XYZ',
'email' => 'xxyz#example.com',
'image' => 'https://lh3.googleusercontent.com//photo.jpg',
'oauth_token' => 'abcdef12345',
'oauth_expires_at' => DateTime.now,
})
OmniAuth.config.add_mock(:google, OmniAuth::AuthHash.new)
get '/auth/":google"/callback'
Rails.application.env_config["omniauth.auth"] = OmniAuth.config.mock_auth[:google]
get '/auth/:google/callback'
end
The error I am getting:
test_validating_a_Google_OAuth_user#SessionsControllerTest (0.49s)
URI::InvalidURIError: URI::InvalidURIError: bad
URI(is not URI?): http://www.example.com:80/auth/":google"/callback
test/test_helper.rb:42:in `setup_omniauth_mock'
Now I followed the documentation here [Oauth Integration Testing][1]
[1]: https://github.com/omniauth/omniauth/wiki/Integration-Testing but I think there is something I am doing wrong.
Can someone please help me guide through this.
Thank you!
J.
I actually resolved it by cleaning things a bit.
My test_helper.rb now:
# OmniAuth auth mock setup for testing
setup do
OmniAuth.config.test_mode = true
Rails.application.env_config["omniauth.auth"] =
OmniAuth.config.mock_auth[:google]
end
#teardown OmniAuth mock setup
teardown do
OmniAuth.config.test_mode = false
end
#Google OAuth mock
def google_oauth2_mock (user)
OmniAuth.config.mock_auth[:google]
OmniAuth::AuthHash.new ({
'provider' => 'google_oauth2',
'uid' => '123545',
'user_id' => '2',
'first_name' => 'X',
'last_name' => 'XXYZ',
'email' => 'xxyzjam#example.com',
'image' => 'https://lh3.googleusercontent.com/photo.jpg',
'oauth_token' => 'abcdef12345',
'refresh_token' => '12345abcdef',
'oauth_expires_at' => DateTime.now,
})
end
I put the routes in the individual tests, and that allowed me to run the tests suite smoothly.
Hope I am able to save you some time and frustrations.
Related
I'm authenticating against LDAP server in my rails application,
the code below is working locally but not on the server.
On the server it throws Net::LDAP::BindingInformationInvalidError (Invalid binding information) when trying to login in the app but works through the console
I'm pretty new to Ruby and can't figure out the proper way to debug it... I know the LDAP configuration is right because i can authenticate and bind from the console or on my local development environment.. I tried to pass :verbose => true to the LDAP constructor but without effect...
require 'net/ldap'
require 'devise/strategies/authenticatable'
module Devise
module Strategies
class LdapAuthenticatable < Authenticatable
def authenticate!
if params[:user]
ldap = Net::LDAP.new :host => 'XX.XX.XX.XX',
:port => 636,
:connect_timeout => 5,
:base => 'CN=Configuration,DC=internal,DC=XX,DC=XX',
:encryption => {
:method => :simple_tls
},
:auth => {
:method => :simple,
:username => ENV['LDAP_USER'],
:password => ENV['LDAP_PASSWORD']
}
result = ldap.bind_as(:base => "OU=Users,OU=XX,DC=XX,DC=XX,DC=XX",
:filter => "(userPrincipalName=#{email})",
:password => password,
)
if result
user = User.find_by(email: email)
success!(user)
else
return fail(:invalid_login)
end
end
end
def email
params[:user][:email]
end
def password
params[:user][:password]
end
end
end
end
Warden::Strategies.add(:ldap_authenticatable, Devise::Strategies::LdapAuthenticatable)
SOLVED
turned out it was the ENV variables that were not read.
Maybe that account is not authorized? Sounds like the problem is in the binding configuration: base => "OU=Users,OU=XX,DC=XX,DC=XX,DC=XX"
More information from other users who encountered this error:
https://gitlab.com/gitlab-org/gitlab-ce/issues/21937
LDAP groups authentication fails: Invalid Binding Information
I have a sample project, where user can login with their google account, Now i want to write a test to verify that user has successfully logged in with his google account. But i don't know how to verify this thing in my test file ?
This is what i have tried now but its not working
OmniAuth.config.mock_auth[:google] = OmniAuth::AuthHash.new({
:provider => 'google',
:uid => '1337',
:info => {
'name' => 'JonnieHallman',
'email' => 'jon#test.com'
}
request.env["devise.mapping"] = Devise.mappings[:user]
request.env["omniauth.auth"] = OmniAuth.config.mock_auth[:google]
I am supposing that after this my page content would change but they are same as before
You can follow the guide on how to do integration tests with Omniauth https://github.com/intridea/omniauth/wiki/Integration-Testing
basically you'll have something like this in your spec/rails_helper.rb
OmniAuth.config.test_mode = true
OmniAuth.config.mock_auth[:xing] = OmniAuth::AuthHash.new({
:provider => 'google',
:uid => '123545',
:info => {
:name => "Test",
:email => "test#test.com"
},
:credentials => {
:token => "token",
:secret => "secret"
}
# etc.
})
And then have a login_helper that does something like
def login
Rails.application.env_config["omniauth.auth"] = OmniAuth.config.mock_auth[:google]
visit root_path
click_link 'loginBtn'
end
(Edit: this code actually works, the error was in my original code, which had an incorrect email address!)
I've figured out how to log into Devise from the console, however when I attempt to do the same from a rake task it gives me 401 unauthorised when posting to sign in. This is my rake task. (These same steps work in the console).
task :get_home => :environment do
app = ActionDispatch::Integration::Session.new Rails.application
app.get '/users/sign_in'
p csrf_token = app.session[:_csrf_token]
app.post '/users/sign_in',{:authenticity_token => csrf_token, :user => {:email => "example#example.com", :password => "password"}}
app.get ''
p csrf_token = app.session[:_csrf_token]
app.get '/users'
File.open("users", "w+") do |f|
f.write(app.response.body)
end
end
User error, I typed in the .con for the email instead of .com.
I must be tired, i double and triple checked the parameters and never noticed this... until an hour later. (i changed the actual email in my post, but in my code it was incorrect)
For newer versions of Rails this still needs parameters specified. This line will toss an error ArgumentError: unknown keywords: authenticity_token, user:
app.post '/users/sign_in',{:authenticity_token => csrf_token, :user => {:email => "example#example.com", :password => "password"}}
To rectify it just add parameters:
app.post '/users/sign_in',{:params => {:authenticity_token => csrf_token, :user => {:email => "example#example.com", :password => "password"}}}
I've tested my controller and have got strange errors like this:
expected: ("376")
got: (376)
Please stub a default value first if message might be received with other args as well.
This is my spec:
it 'should send confirm-email if information is good' do
sign_in user
allow(Order).to receive(:find).with(order.id.to_s).and_return(order)
allow(order).to receive(:finalize) {order}
allow(order.errors).to receive(:empty?) {true}
expect(OrderMailer).to receive_message_chain(:send_finish_notification, :deliver)
patch :save_order, {:id => order.id , :order => {:street_address => 'Baker street', :apt => '123#', :zip_id => zip.id, :frequency_id => frequency.id, :amount_per_hour => '5',
:extras_ids => '', :phone_number => '3213', :credit_card_number => '4242424242424242', :credit_card_cvv => '777',
:credit_card_expiration => '12/20', :source_information => ''}}
end
And I've got this error in some logically close specs. But some tests passes, like this one:
it 'should not update user data if order errors is not empty' do
sign_in user
allow(Order).to receive(:find).with(order.id.to_s).and_return(order)
allow(order).to receive(:finalize) {order}
allow(order.errors).to receive(:empty?) {false}
expect(User).to_not receive(:update_user_data)
patch :save_order, {:id => order.id, :order => {:street_address => 'Baker street', :apt => '123#', :zip_id => zip.id, :frequency_id => frequency.id, :amount_per_hour => '5',
:extras_ids => '', :phone_number => '3213', :credit_card_number => '4242424242424242', :credit_card_cvv => '777',
:credit_card_expiration => '12/20', :source_information => ''}}
end
to_s or to_i doesn't help. The error line in controller -
#order = Order.find(params[:id]
So what could be in that case ? 'Cause it looks like some specs passes, but similar to them don't. Any suggestions ?
I'm trying to get some cucumber tests of omniauth with Facebook working.
Currently I get the following error:
Given I am not logged in # features/step_definitions/user_steps.rb:79
When I go to the homepage # features/step_definitions/web_steps.rb:51
And I follow "Sign in" # features/step_definitions/web_steps.rb:61
Then I should see "Facebook" # features/step_definitions/web_steps.rb:110
When I sign in with facebook # features/step_definitions/omniauth_steps.rb:1
undefined method `[]=' for nil:NilClass (NoMethodError)
(eval):2:in `click_link'
./features/step_definitions/web_steps.rb:62:in `/^(?:|I )follow "([^"]*)"$/'
features/users/login_with_facebook.feature:14:in `When I sign in with facebook'
Then I should be signed in # features/step_definitions/user_steps.rb:60
I have the following omniauth_steps.rb file
Given /^I sign in with facebook$/ do
step %{I follow "Facebook"}
end
And support/omniauth.rb
Before('#omniauth_test') do
OmniAuth.config.test_mode = true
p "OmniAuth.config.test_mode is #{OmniAuth.config.test_mode}"
OmniAuth.config.mock_auth[:facebook] = {
:provider => 'facebook',
:uid => '1234567',
:info => {
:nickname => 'jbloggs',
:email => 'joe#bloggs.com',
:name => 'Joe Bloggs',
:first_name => 'Joe',
:last_name => 'Bloggs',
},
:credentials => {
:token => 'ABCDEF...', # OAuth 2.0 access_token, which you may wish to store
:expires_at => 1321747205, # when the access token expires (if it expires)
:expires => true # if you request `offline_access` this will be false
},
:extra => {
:raw_info => {
:id => '1234567',
:name => 'Joe Bloggs',
:first_name => 'Joe',
:last_name => 'Bloggs',
:username => 'jbloggs',
:email => 'joe#bloggs.com',
}
}
}
end
After('#omniauth_test') do
OmniAuth.config.test_mode = false
end
When I do manual tests, everything works, so I'm happy my configuration is ok, this is just belt and braces. The error message isn't too informative so I'm hoping that someone can stop an obvious flaw! I'm running the latest gems for rails, devise, omniauth and omniauth-facebook.
Edit
Looking at the logs, I see this in the development log:
Started GET "/users/auth/facebook" for 127.0.0.1 at 2012-02-22 14:52:16 +0100
Processing by Users::SessionsController#setup as HTML
Rendered text template (0.0ms)
Completed 404 Not Found in 2ms (Views: 0.6ms | ActiveRecord: 0.2ms)
Started GET "/users/auth/facebook/callback?code=AQ<snip>IE" for 127.0.0.1 at 2012-02-22 14:52:18 +0100
Processing by Users::SessionsController#setup as HTML
The test log is different, I get two 404s. The first is legit (I use a custom Omniauth setup) but the second is calling "users/auth/facebook" again instead of "/users/auth/facebook/callback"