Using erb in database.yml breaks Devise - ruby-on-rails

I updated by database.yml to get credentials out of the file for security purposes, and replaced them with a call via erb to an object that reads the info from a file.
This seems to work fine when authentication isn't involved, but when devise generated views seem to break.
This version of database.yml that breaks it:
development:
adapter: sqlserver
host: my_server.xxx.rds.amazonaws.com
port: 1433
database: MyDatabase
username: <%= CredentialsManager.get_db_user %>
password: <%= CredentialsManager.get_db_pass %>
But the console, and pages that don't call authentication have no problem accessing model attributes.
However views like devise/sessions/new.html.erb, seem to be looking in the wrong place for the User model. Form breaks with errors like these, where the user model appears to have no 'email' attribute:
Processing by Devise::SessionsController#new as HTML
Rendered devise/sessions/new.html.erb within layouts/application (6.0ms)
Completed 500 Internal Server Error in 18ms
ActionView::Template::Error (undefined method `email' for #<User >):
3: <%= form_for(resource, :as => resource_name, :url => session_path(resource_name)) do |f| %>
4: <div><%= f.label :email %>
5: <br/>
6: <%= f.email_field :email %></div>
7:
8: <div><%= f.label :password %>
9: <br/>
app/views/devise/sessions/new.html.erb:6:in `block in _app_views_devise_sessions_new_html_erb__882742671_47657856'
app/views/devise/sessions/new.html.erb:3:in `_app_views_devise_sessions_new_html_erb__882742671_47657856'
Rendered C:/Ruby193/lib/ruby/gems/1.9.1/gems/actionpack-3.2.11/lib/action_dispatch/middleware/templates/rescues/_trace.erb (1.0ms)
Rendered C:/Ruby193/lib/ruby/gems/1.9.1/gems/actionpack-3.2.11/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb (1.0ms)
Rendered C:/Ruby193/lib/ruby/gems/1.9.1/gems/actionpack-3.2.11/lib/action_dispatch/middleware/templates/rescues/template_error.erb within rescues/layout (16.0ms)
Examining the |f| parameter in the debugger shows that it has an #object attribute of class User, but the #attributes hash of #object is an empty hash, and #column_names is an empty array.
Does anyone have an idea how to fix this? I need to get credentials out of database.yml, and this is the way I'd like to do it.
Environment Rails 3.2.11
Devise 2.1.2
Warden 1.2.1

This problem was resolved by changing the db username from 'asadmin_app' to just 'asadmin'
No idea why devise doesn't like db usernames with underscores, but it seems like some kind of bug to me. Rails itsef, and SQL Server (the backing DB) have no problem with _ in a username, but soemthing goes screwy when devise and warden get involve.d

Related

Request in Capybara a GET, when it should be a POST

So this is a pretty basic Rails 5 application using Docker, which includes some user authentication that I built from scratch (not using Devise etc). Now, I want to start learning about request specs with Capybara, but I'm hitting what seems like a pretty strange issue with it.
Here's my login form (sessions.new.erb):
<%= form_tag sessions_path do %>
<form class="m-t" role="form" action="/">
<div class="form-group">
<%= text_field_tag :email, params[:email], class: 'form-control', placeholder: "Email Address", required: "" %>
</div>
<div class="form-group">
<%= password_field_tag(:password, nil, class: 'form-control', placeholder: "Password", required: "") %>
</div>
<div class="form-group">
<%= check_box_tag :remember_me, 1, params[:remember_me] %>
<%= label_tag :remember_me %>
</div>
<div class="actions"><%= submit_tag "Log In", class: "btn btn-primary block full-width m-b" %></div>
</form>
<% end %>
And my requests/sessions_spec.rb:
require "rails_helper"
RSpec.feature "Login", :type => :feature do
scenario "handles wrong email and password gracefully" do
visit login_path
fill_in "Email Address", :with => "something"
fill_in "Password", :with => "something"
click_button "Log In"
expect(page).to have_text("Email or password incorrect")
end
end
Now, this works if you test it manually so I would presume Capybara would see the same thing. But it kept failing. I've got the application configured so that if you try and access a protected controller and you're not logged in, it redirects you to /login and flashes a message to say Please log in to see this page. The Rspec test was returning that, which was weird - that suggested that Capybara was trying to visit another page.
So I tailed the test logs (docker-compose run web tail -f log/test.log)
And what I found is puzzling me:
Started GET "/login" for 127.0.0.1 at 2017-10-17 06:59:26 +0000
Processing by SessionsController#new as HTML
Rendering sessions/new.html.erb within layouts/empty
Rendered sessions/new.html.erb within layouts/empty (1.1ms)
Completed 200 OK in 6ms (Views: 6.1ms | ActiveRecord: 0.0ms)
Started GET "/?email=something&password=[FILTERED]&commit=Log+In" for 127.0.0.1 at 2017-10-17 06:59:26 +0000
Started GET "/locations" for 127.0.0.1 at 2017-10-17 06:59:26 +0000
Processing by LocationsController#index as HTML
Redirected to http://www.example.com/login
Filter chain halted as :authenticate rendered or redirected
Completed 302 Found in 2ms (ActiveRecord: 0.0ms)
Started GET "/login" for 127.0.0.1 at 2017-10-17 06:59:26 +0000
Processing by SessionsController#new as HTML
Rendering sessions/new.html.erb within layouts/empty
Rendered sessions/new.html.erb within layouts/empty (1.1ms)
Completed 200 OK in 6ms (Views: 4.9ms | ActiveRecord: 0.0ms)
(0.4ms) ROLLBACK
The first bit is okay, GET Login is processed by the SessionsController#new. But then, (see line 6) for some reason Capybara tried to GET the root URL, passing the email/password params in. My root URL is mapped to the LocationsController#index, which the user isn't allowed to access, so gets redirected back to /login with the message Please log in to see this page. What that button actually does is send a POST to SessionsController#create. And if you watch the logs when you do it manually, that's exactly what happens:
web_1 | Started POST "/sessions" for 172.18.0.1 at 2017-10-17 07:02:19+0000
web_1 | Processing by SessionsController#create as HTML
I can't work out why in Capybara when you press the button it performs a completely different request to when you click the button manually.
Help greatly appreciated!
A couple of clarifications first.
You're not writing request specs, you're writing feature specs (as evidenced by the use of RSpec.feature and :type => :feature
You don't need to specify :type => :feature when using RSpec.feature since that's already set.
Now on to your issue. You have nested forms in your view code since form_tag creates a <form>element and then you have another <form> element directly inside that (Note: it's always better to post the actual HTML rather than the erb so people can see what the actual HTML is). Combine that with the fact you appear to be using the rack-test driver (no js: true metadata) which won't behave the same way as a real browser when the HTML is invalid (which nested forms are), and you end up with your current behavior. I would guess when you use it with a real browser the inside form element is ignored and the outer form element has a method attribute equal to "post" so it gets posted. When using rack-test it's probably submitting the inner form element which has no method attribute and therefore defaults to "get". Remove the extraneous <form class="m-t" role="form" action="/"> form element from your view and things should work.

Impossible to delete a flash

I made a mistake before migrating a plugin, and have written
flash[:notice] = :label_presta_added
instead of
flash[:notice] = l(:label_presta_added)
I corrected my mistake but it seems that my Redmine Plugin has trashed my Redmine. Even though I delete my plugin a migrate once again, I still get this error:
Started GET "/" for 127.0.0.1 at 2016-06-01 22:21:37 +0200
Processing by WelcomeController#index as HTML
Current user: admin (id=1)
Rendered welcome/index.html.erb within layouts/base (28.1ms)
Completed 500 Internal Server Error in 366ms (ActiveRecord: 116.0ms)
ActionView::Template::Error (undefined method `html_safe' for :label_presta_added:Symbol
Did you mean? html_safe?):
97: <div id="sidebar">
98: <%= yield :sidebar %>
99: <%= view_layouts_base_sidebar_hook_response %>
100: </div>
101:
102: <div id="content">
103: <%= render_flash_messages %>
app/helpers/application_helper.rb:312:in `block in render_flash_messages'
app/helpers/application_helper.rb:311:in `render_flash_messages'
app/views/layouts/base.html.erb:100:in `_app_views_layouts_base_html_erb__4104276684161420982_39604440'
lib/redmine/sudo_mode.rb:63:in `sudo_mode'
Can somebody give me a hand here?
Thanks in advance!
This is stored in your session, so usually changing the session secret key will invalidate all sessions and discard any old session data.
You can also try and rescue to clear it out as a one-time deal.
Have you restarted the server? Or you can use flash[:notice] = nil to remove it.
It looks like it throws a html_safe error. Can you see if the method which is rendering the flash is using html_safe? It looks like its coming from there.
Not sure exactly, may be shooting in the dark.
But read these and try may be:
actionview::template::error(undefined method 'html_safe' for nil:NilClass)
http://www.redmine.org/issues/8477

Devise warden 401 Unauthorized when wrong credentials

I have a quite standard Devise login procedure with:
View:
resource_name, :url => session_path(resource_name)) do |f| %>
<%= f.input :password, input_html: {class: "span6"} %>
<% if devise_mapping.rememberable? -%>
<p><%= f.check_box :remember_me %> Remember me</p>
<% end -%>
<input type="hidden" name="after_sign_in_page" value="<%=#after_sign_in_page%>">
<p><%= f.submit "Sign in", class: "btn btn-success" %></p>
And I just created a sessioncontroller to downcase the email:
class SessionsController < Devise::SessionsController
def create
params[:user][:email].downcase!
super
logger.debug "Errors: #{resource.errors}"
end
A login with good credentials happens fine.
With wrong credentials, It redirects to the sign-in page with this log:
Started POST "/users/sign_in" for 127.0.0.1 at 2013-01-10 09:59:44 +0100
Processing by SessionsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"8eytQkr20JOOOdDvpCWakbmUzNoaHMxK9/BSEVxETik=", "user"=>{"email"=>"nicolas#demoreau.be", "password"=>"[FILTERED]", "remember_me"=>"0"}, "after_sign_in_page"=>"", "commit"=>"Sign in"}
Time zone: (GMT+00:00) UTC, current area: , user to register: , current controller: sessions
Completed 401 Unauthorized in 69ms
Processing by SessionsController#new as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"8eytQkr20JOOOdDvpCWakbmUzNoaHMxK9/BSEVxETik=", "user"=>{"email"=>"nicolas#demoreau.be", "password"=>"[FILTERED]", "remember_me"=>"0"}, "after_sign_in_page"=>"", "commit"=>"Sign in"}
Rendered devise/sessions/_new.html.erb (17.8ms)
Rendered devise/sessions/new.html.erb within layouts/application (19.7ms)
Rendered layouts/_header.html.erb (66.1ms)
Completed 200 OK in 173ms (Views: 98.3ms | ActiveRecord: 0.9ms)
Apparently the 401 is dropped by Warden but I couldn't figure out why.
The user is correctly redirected back to the login page but there is no error message displayed (which is normal as they are wiped out by the redirect)
What am I doing wrong?
thanks!
EDIT 1:
For now, I found a quick hack. I added this in SessionsController#new
if params[:user]
flash[:alert] = "Incorrect login or password"
end
Not very elegant but at least, I have something.
First of all, let me advice you against overriding Devise controllers:
In this case, Devise takes care of transforming the email to lower
case for you, so there's really no need to overwrite the create method.
Your app will support Devise updates seamlessly if you stick to the
standard.
Also, Devise should set a flash error automatically, make sure you're displaying it in your view.
The status code 401 is just a standard response for unauthorized requests.
401 Unauthorized is similar to 403 Forbidden, but specifically for use
when authentication is required and has failed or has not yet been
provided
http://en.wikipedia.org/wiki/List_of_HTTP_status_codes
You should definitely consider dropping your custom controller,
Cheers
Your flash message is not going to be set because Devise::SessionsController#create calls warden for the authentication which, in case of failures, will call Devise::FailureApp. Your controller never handles the failure scenarios.
If you want a custom message, you can customize the failure app for that, there are some articles in the Devise wiki explaining how to do so.
But in general, you can customize your failure messages via I18n and there is probably a better way to achieve what you want without a need to override Devise controllers.
I agree with jassa, just update your Devise version (with bundle update devise).
Case insensitive emails are already present in Devise, just make sure you have this config:
# devise.rb
Devise.setup do |config|
config.case_insensitive_keys = [:email ]
end
In any case, since you seem to be missing some flash messages and this config, perhaps it would better if you just re-ran the generator:
rails generate devise:install
You should then let Devise overwrite some files, just make sure you backup yours first.

Why is the wrong action processing my .ajax request.

This is an issue I have been working around for some time now thinking I would eventually stumble on an explaination. I have not and it's now becoming a little more problematic for me.
I used rails-generate-scaffold to create a simple (users and posts) application. This was done after installing jquery and jquery-ui. I added actions "login" and "auth" to the users controller. Login.html.erb contains some javascript that sends .ajax request to the users#auth action passing the login information (email and password) as parameters.
The the template auth.js.erb exists. The "auth" action responds to format.js. The request looks normal, but rails processes the request with the "show" action rather than the "auth" action.
In other words, a request to userscontrollers#auth (via .ajax) is being processed by userscontroller#show (as JS).
The problem goes away if I remove the "resources :users" route that scaffold added (the correct action is then called). But without this route other useful scaffold stuff becomes unuseable (like users#new).
From Gemfile: gem 'jquery-rails', '>=0.2.6'
Installed jQuery with: rails generate jquery:install --ui
From ../layouts/application.html.erb
<head>
<title>Tab1</title>
<%= stylesheet_link_tag :all %>
<%= stylesheet_link_tag 'jquery-ui-1.8.16.custom.css' %>
<%= javascript_include_tag :defaults %>
<%= javascript_include_tag 'jquery.min.js' %>
<%= javascript_include_tag 'jquery.min.js', 'jquery-ui.min.js' %>
<%= csrf_meta_tag %>
</head>
Here is ./log/development.log to shows the request and the response.
Started GET "/users/auth/?email=steve&password=[FILTERED]&_=1326063255777" for 24.11.242.181 at 2012-01-08 17:53:45 -0500
Processing by UsersController#show as JS
Parameters: {"email"=>"steve", "password"=>"[FILTERED]", "_"=>"1326063255777", "id"=>"auth"}
^[[1m^[[36mUser Load (0.2ms)^[[0m ^[[1mSELECT `users`.* FROM `users` WHERE `users`.`id` = 0 LIMIT 1^[[0m
Completed 404 Not Found in 6ms
ActiveRecord::RecordNotFound (Couldn't find User with ID=auth):
app/controllers/users_controller.rb:43:in `show'
Suggests that the request --> GET "/users/auth/?email ... is being processed by UsersController#show as JS
Thanks

Getting "undefined method `password' for #<User:0x2b95caea8590>" with Authlogic

I realize there's a nearly identical question about this here but the fix there did not fix my problem.
My Authlogic is working in my development environment but not in my production environment. Below is the error I'm getting.
Started GET "/users/new" for 71.205.207.120 at Tue Feb 22 19:24:49 -0800 2011
Processing by UsersController#new as HTML
Rendered users/_form.html.erb (19.3ms)
Rendered users/new.html.erb within layouts/application (21.6ms)
Completed in 38ms
ActionView::Template::Error (undefined method `password' for #<User:0x2b95caea8590>):
21: </div>
22: <div class="field">
23: <%= f.label :password %><br />
24: <%= f.password_field :password %>
25: </div>
26: <div class="field">
27: <%= f.label :password_confirmation %><br />
app/views/users/_form.html.erb:24:in `_app_views_users__form_html_erb___1397135998_23961177217120_1124190'
app/views/users/_form.html.erb:1:in `_app_views_users__form_html_erb___1397135998_23961177217120_1124190'
app/views/users/new.html.erb:3:in `_app_views_users_new_html_erb___1081160896_23961177226000_0'
app/controllers/users_controller.rb:29:in `new'
I didn't misspell any of the database columns, I'm already doing acts_as_authentic and I have restarted my server, so I'm not sure what else to try. It seems like it must be something to do with my database but my database structure seems to be identical.
Database password field (and/or salt field) may not match any of the defaults!!!
I've had this problem twice now and in both cases it was tricky because of two things:
1) The message "undefined method 'password' really (often) means password field not found in database using defaults.
2) The location to ADD your database field for password (or salt for that matter) is NOT anywhere in your applications directory, it in your ruby gem directory, something like ~/.gem/ruby/1.8/gems/authlogic-2.1.6/lib/authlogic/acts_as_authentic !
The field to change is password.rb. Add your field name(s) in to the list, e.g. i added pd_hashed changed:
module Config
# The name of the crypted_password field in the database.
#
# * Default: :crypted_password, :encrypted_password, :password_hash, or :pw_hash
# * Accepts: Symbol
def crypted_password_field(value = nil)
rw_config(:crypted_password_field, value, first_column_to_exist(nil, :pd_hashed, :crypted_password, :encrypted_password, :password_hash, :pw_hash))
end
Do the same for the salt field.
Restart and this may help.

Resources