Logging into Devise from a Rake Task - ruby-on-rails

(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"}}}

Related

Why ldap bind is failing on server?

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

Oauth minitest error, callback link giving an error

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.

undefined method error trying to get cucumber testing of omniauth working properly

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"

What are the right parameters for a rspec put request on my stub

I have a controller spec and I get following failed expectation:
Failure/Error: put :update, :id => login_user.id, :user => valid_attributes
#<User:0xbd030bc> received :update_attributes with unexpected arguments
expected: ({:name=>"changed name", :email=>"changed#mail.com", :password=>"secret", :password_confirmation=>"secret"})
got: ({"name"=>"Test user", "email"=>"user#test.com", "password"=>"secret", "password_confirmation"=>"secret"})
And for me it looks like I am passing in "name" => "Test User" and I am expecting :name => "test user"
my spec looks like this:
describe 'with valid parameters' do
it 'updates the user' do
login_user = User.create!(valid_attributes)
controller.stub(:current_user).and_return(login_user)
User.any_instance.
should_receive(:update_attributes).
with(valid_attributes.merge(:email => "changed#mail.com",:name=>"changed name"))
put :update, :id => login_user.id, :user => valid_attributes
end
end
and I have something like this for my valid attributes:
def valid_attributes
{
:name => "Test user",
:email=> "user#test.com",
:password => "secret",
:password_confirmation => "secret"
}
end
so what is wrong with my parameters any suggestions?
I am using Rails 3.0.5 with rspec 2.6.0...
The failure message is telling you exactly what's going on: any instance of User is expecting update_attributes with a hash including :email => "changed#mail.com", but it's getting :email => "user#test.com" because that's what's in valid_attributes. Similarly, it's expecting :name => "changed_name", but gets :name => "Test user" because that's what's in valid_attributes.
You can simplify this example and avoid this confusion. There is no need to use valid_attributes here because should_receive intercepts the update_attributes call anyhow. I usually do this like so:
controller.stub(:current_user).and_return(mock_model(User)) # no need for a real user here
User.any_instance.
should_receive(:update_attributes).
with({"these" => "params"})
put :update, :id => login_user.id, :user => {"these" => "params"}
This way the expected and actual values are right in the example and it makes clear that it doesn't really matter what they are: whatever hash is passed in as :user is passed directly to update_attributes.
Make sense?

rails render_to_string problem

I`m trying to test my controller with rspec and always get an error.
users_controller.rb:
def update
#user.update_attributes!(params[:user])
redirect_to #user, :status => 202, :text => render_to_string(:partial => "users/show", :type => "json", :locals => {:user => #user})
#notice, that redirect_to was reinitialized and :text is a parameter for response_body
end
_show.tokamak
user {
id user.id
email user.email
username user.username
}
spec file
it "should NOT update user username" do
username = #user.username
put 'update', :id => #user.id, :user => {:username => username+"abc"}, :format => :json
response.status.should be(202)
response.headers["Location"].length.should be > 0
puts response.body
#user.reload
#user.username.should eq(username)
end
end
So I get an error:
Failure/Error: put 'update', :id =>
#user.id, :user => {:username =>
username+"abc"}, :format => :json
ActionView::Template::Error:
You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.[]
# C:/Users/makaroni4/free_frog/ffapi/app/views/users/_show.tokamak:1:in
_app_views_users__show_tokamak___509498818
_32151168_368311673'
# C:/Users/makaroni4/XXX/XXX/app/controllers/users_controller.rb:22:in
update'
# ./users_controller_spec.rb:34:in
`block (4 levels) in '
So may be I call render_to_string method wrong?
Try stubbing out find?
mock_user = User.stub(:find).with(#user.id) {#user}
To be honest I'd go a few steps further and make sure you mock and stub most of the relevant behavior of the User object (or whatever class #user is). Keep in mind you're only testing that the controller action returns what you expect if you give it valid input--not that the model itself does the right thing.
I had a lot of difficulty wrapping my head around the differences in model vs. controller specs...
I hope this helps...if not, I apologize in advance...
EDIT:
I'll take this a step futher and suggest this test is actually a model test. The actual controller test would be something like as the way your spec test should behave:
it "should NOT update user with invalid input" do
mock_user = mock_model(User, {}).as_null_object
User.stub(:find).with("12") {mock_user}
User.stub(:update_attributes).with({}).and_return(false)
put 'update', :id => "12"
# test that your output is correct, or even if the render target is what you expect.
end

Resources