Password showing in production.log - ruby-on-rails

Using Rails 2.3.8.
I have added this in my controller:
filter_parameter_logging :password, :password_confirmation
But password is still showing in my production and development logs. Please advise.
Processing UserSessionsController#create (for 110.159.52.119 at 2011-03-11 18:25:50) [POST]
Parameters: {"user_session"=>{"remember_me"=>"0", "password"=>"therealpassword", "login"=>"usernamehere"}, "action"=>"create", "authenticity_token"=>"kx96Yc9sF/dYbRL8UYni2tp+p/yz6CTHw+j/X6bqh/g=", "controller"=>"user_sessions"}
[paperclip] Saving attachments.
Redirected to http://abc.com/account
Completed in 2047ms (DB: 532) | 302 Found [http://abc.com/user_session]
** Erubis 2.6.6
Thanks.

For others' reference: filter_parameter_logging is deprecated in Rails 3.
From the Devise tutorial:
"
PREVENT LOGGING OF PASSWORDS
We don’t want passwords written to our log file. In Rails 2, we would change the file
app/controllers/application_controller.rb
to include:
filter_parameter_logging :password, :password_confirmation
In Rails 3, this is deprecated and instead we modify the file config/application.rb to include:
config.filter_parameters += [:password, :password_confirmation]
Note that filter_parameters is an array.
"

Add filter_parameter_logging to the UserSessionsController and restart you app.

Related

How to print current username to log file in Rails.

Recently, I find out tagged logger. It is a very useful option and I config in production environment.
# config/environments/production.rb
...
config.log_tags = [ :uuid,:remote_ip ]
...
# log/production.log
[4d23e817-eca8-4db1-ba5b-7456d3af7f65] [127.0.0.1] Started GET "/resources/id" for 127.0.0.1 at 2015-11-26 21:09:11 +0900
I also want to print current login user name to log file, so I tried and found a link How to log user_name in Rails?.
But It's not working for me.
I'm using devise and rails4. How do I print?
Thanks in advance.
You can use a different approach. I've used the following one:
In application_controller.rb:
before_action: print_current_user
def print_current_user
if user_signed_in?
Rails.logger.debug "UserId: #{current_user.id}"
end
end
Or, you can use the lograge gem.

Mongodb error code 10068 or 17287 with rails 4.1 and devise

I'm trying to use mongoid with Rails 4.1.0 app and am getting error 17287 on moongodb 2.6.0 (same as 10068 on earlier versions of mongodb).
Here is the error message:
The operation: #<Moped::Protocol::Query #length=127 #request_id=5 #response_to=0 #op_code=2004 #flags=[] #full_collection_name="educandose_development.users" #skip=0 #limit=-1 #selector={"$query"=>{"_id"=>{"$oid"=>BSON::ObjectId('534d6f4f6372618443000000')}}, "$orderby"=>{:_id=>1}} #fields=nil> failed with error 17287: "Can't canonicalize query: BadValue unknown operator: $oid" See https://github.com/mongodb/mongo/blob/master/docs/errors.md for details about this error.
Any idea of what could be wrong?
After looking for a while, I realized that the new json cookies serializer on rails 4.1 breaks moped queries on devise resources.
To fix that, remove the following line on the cookies_serializer.rb initializer
Rails.application.config.action_dispatch.cookies_serializer = :json
You may want to get the old sessions_store.rb file back with content similar to:
YourApp::Application.config.session_store :cookie_store, key: '_yourapp_session'
or try the master branch of devise.
Take a look here: https://github.com/plataformatec/devise/issues/2949#issuecomment-40520236
and here: https://github.com/plataformatec/devise/pull/2882
Temporarily, until moped/session/json formatting is fixed, I'm using:
# app/models/concerns/zero_oid_fix.rb
module ZeroOidFix
extend ActiveSupport::Concern
module ClassMethods
def serialize_from_session(key, salt)
record = to_adapter.get((key[0]["$oid"] rescue nil))
record if record && record.authenticatable_salt == salt
end
end
end
And in devise model:
class User
devise :database_authenticatable, ...
# NOTE: Has to be after devise
include ZeroOidFix
...
end
Hope this answer will get obsolete fast.
Comment out the line below from the cookies_serializer.rb
Rails.application.config.action_dispatch.cookies_serializer = :json
Delete cookies.
Restart server.
Worked for me on "rails 4.1.4, devise 3.2.4, mongoid 4.0.0"

Having issue post migration to rails 3.2.5 - resource.save not working, data is not saving

We have recently migrated from rails 3.2.3 to Rails 3.2.5 and we are using Devise 2.0.4. In our application we have override the Devise controller just to utilize the omniauth with devise.
When we were using 3.2.3 version on Sign_UP everything was working fine as soon as we migrated to 3.2.5 resource.save stopped working, it does not show any failure or success message, just redirects to sign_in page
After that I tried resource.save! so that I could get the exact erorr, it raised following error message, but this is not true as in the Table there is no such record and even current content is also not saved
Completed 500 Internal Server Error in 1626644ms
ActiveRecord::RecordInvalid (Validation failed: User name has already been taken):
I have also tried it with Devise 2.1 and got the same result.
I have found the problem area. But it is little strange
In our current working Rails 3.2.3 app and we have this validation in our model, this is failing in the Rails 3.2.5
validates :user_name, :uniqueness => true
Reason is - User_name in the table as "nil" already available, and when next time we try to insert "user_name" as NIL it is checking for uniqueness of NIL and there it fails.
To fix this I have added :allow_nil option, but still my question is why did not it fail for rails 3.2.3
validates :user_name, :uniqueness => true, :allow_nil => true

Ruby on Rails 3: Devise::LdapAdapter.get_ldap_param undefined method error

I am running:
Ruby 1.9.3p0,
Rails 3.1.1,
Devise 1.4.9,
Devise_ldap_authenticatable 0.4.10
I am using Devise to authenticate my Rails application via an ldap server. I am using username instead of email to authenticate, so naturally the email field in my table is blank.
To query the ldap for email, the official way is to add this code in the user model:
before_save :get_ldap_email
def get_ldap_email
self.email = Devise::LdapAdapter.get_ldap_param(self.username,"mail")
end
This code fails, without attempting to do anything with the ldap, with this:
undefined method `mail' for nil:NilClass
It refers to the line inside the method definition. The log output is no more helpful:
Started POST "/users/sign_in" for 10.50.1.96 at 2011-11-15 11:18:16 -0800
Processing by Devise::SessionsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"<hidden>=", "user"=>{"username"=>"<hidden>", "password"=>"[FILTERED]", "remember_me"=>"0"}, "commit"=>"Sign in"}
User Load (0.9ms) SELECT "users".* FROM "users" WHERE "users"."username" = '<hidden>' LIMIT 1
LDAP: LDAP dn lookup: uid=<hidden>
LDAP: LDAP search for login: uid=<hidden>
LDAP: Authorizing user <hidden>
LDAP: LDAP dn lookup: uid=<hidden>
LDAP: LDAP search for login: <hidden>
Completed 500 Internal Server Error in 251ms
NoMethodError (undefined method `mail' for nil:NilClass):
app/models/user.rb:14:in `get_ldap_email'
All lines previous to the 500 error are normal LDAP successful authentication that are unrelated to the the email query.
I started learning Ruby, Rails, and Devise just last week, so I'm not sure what files would be the most telling, but here is my user.rb model and gemfile:
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :token_authenticatable, :encryptable, :confirmable, :lockable, :timeoutable and :omniauthable
devise :ldap_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
before_save :get_ldap_email
# Setup accessible (or protected) attributes for your model
attr_accessible :email, :username, :password, :password_confirmation, :remember_me
def get_ldap_email
self.email = Devise::LdapAdapter.get_ldap_param(self.username,"mail")
end
end
And the gemfile:
source 'http://rubygems.org'
gem 'rails', '3.1.1'
# Bundle edge Rails instead:
# gem 'rails', :git => 'git://github.com/rails/rails.git'
gem 'sqlite3'
<... unrelated ...>
gem 'therubyracer', :platforms => :ruby
gem "devise"
gem "devise_ldap_authenticatable"
I have tried restarting the server, and have done a bundle install since the last GemFile update. My configuration has ldap_create_user = true and username is the correct field name in users. Is there an error in that method? Could there be a version incompatibility? I'm not really sure what else to check, and rails is giving me nothing beginner-friendly to go on. I would love some help with this.
I'm also having this problem - my current temporary solution is to fetch the data myself using Net::LDAP instead of the ldap_authenticatable classes. The more permanent solution would, of course, be to patch ldap_authenticatable, which I may try to do next.
The issue (at least for me) was this: After poring through the ldap_authenticatable code (namely ldap_adapter.rb) I discovered that the get_ldap_param method is not authenticating with the server when trying to fetch the params unless admin_user and admin_password are specified in ldap.yml. So, if your LDAP server allows anonymous reading of data, then get_ldap_param will work as advertised. On OpenLDAP (which is what I use for local testing), anonymous read access is set with the "access to" property in slapd.conf:
access to *
by anonymous auth
But, my corporate LDAP does not allow that.
The Net::LDAP instance in ldap_authenticatable needs to be created with auth parameters when being used for parameter fetching, but it's not. No auth parameters are given, so no results are returned.
So, temporarily, I have the following code in my User model, calling get_ldap_data as a before_save filter:
def has_ldap_data?
[self.email, self.first_name, self.last_name].none? {|v| v.nil?}
end
def get_ldap_data
return true if has_ldap_data? or self.password.nil?
ldap = create_ldap
ldap.search(
:base => ldap.base,
:attributes => ['cn', 'sn', 'givenname', 'mail'],
:filter => Net::LDAP::Filter.eq('cn', self.username),
:return_result => true) do |entry|
self.email = entry.mail.first
self.first_name = entry.givenname.first
self.last_name = entry.sn.first
end
has_ldap_data?
end
def create_ldap(password = nil)
ldap_config = ldap_config = YAML.load(ERB.new(File.read(::Devise.ldap_config || "#{Rails.root}/config/ldap.yml")).result)[Rails.env]
ldap_options = {
:host => ldap_config["host"],
:port => ldap_config["port"],
:base => ldap_config["base"],
:auth => {
:method => :simple,
:username => "cn=#{self.username},#{ldap_config['base']}",
:password => password || self.password
}
}
ldap_config["ssl"] = :simple_tls if ldap_config["ssl"] === true
ldap_options[:encryption] = ldap_config["ssl"].to_sym if ldap_config["ssl"]
Net::LDAP.new(ldap_options)
end
Modify per your particular needs. It's not ideal, but works for now until forking/patching ldap_authenticatable to account for this use case.
So here's the problem and a potential solution.
ldap_get_param assumes that anonymous read access to the LDAP server is allowed, and thus tried to bind and read with {:method => :anonymous}. If your server does not allow anonymous searches, and eg. Active Directory does not by default, then your call will fail with the obscure error message above, which is really trying to say "no matching results".
Unfortunately, devise_ldap_authenticable does not allow you to require authentication for read operations, so I went and forked a copy that does. To use it instead, slot this into your Gemfile instead of the original:
gem 'devise_ldap_authenticatable', :git => 'https://github.com/jpatokal/devise_ldap_authenticatable.git'
And then call get_ldap_param like this:
Devise::LdapAdapter.get_ldap_param(self.login,"mail",self.password)
Note the 3rd parameter there. I've also submitted this as a pull request to master, and you can track the issue here: https://github.com/cschiewek/devise_ldap_authenticatable/issues/94
I'm afraid I don't got the answer for you, but I can tell you that I'm getting the same exact error as you.
I've done a couple of posts here at StackOverflow but haven't gotten any answers. Everything works fine for me until I try to pull extra attributes and :before_save. I've traced my eDir server with ndstrace and it says the question it gets is empty?! So it seems that my selected attribute is not passed down to the ldap server.
Probably this is related to the version you are using.
Inspecting the git repository of the project, I see that the method get_ldap_param has been introduced with version 0.4.7.
Check that you have no constraints on the version of the devise_ldap_authenticatable gem in your Gemfile, and remove them in the case, then run
$ bundle update devise_ldap_authenticatable
it should update your gem to version 0.6.0 (with devise 2.0.1), and the method is present and working.
You could also specify a minimum version in the Gemfile, if you think it is the case:
gem 'devise_ldap_authenticatable', '~> 0.4.7'

The I18N is abnormal when my rails app in production environment

I write a rails app in my local machine(OSX 10.6.6,Rails 3.0.1,WEBrick),All I18n files work fine.when i push the app to my web server(Centos5.4,Rails 3.0.1,Phusion Passenger version 3.0.2) I get a error"Translation missing: en, username_exist"
My model code:
validates_uniqueness_of :username, :on => :create, :message => I18n.t("username_exist")
My i18n file(config/locales/en.yml):
en:
username_exist: "username exist"
I think the model not found i18n file?
When you use I18n.t at class scope, as you are doing in the call to validates_uniqueness_of, it will be evaluated when the file is loaded. That's probably not what you want, because it means the message will always appear in the default locale, rather than using the locale of the user making each request. It may also be causing the problem you are seeing, if the file is loaded before I18n is configured.
Instead, use a symbol:
validates_uniqueness_of :username, ..., :message => :username_exist
And see the documentation for ActiveModel::Errors#generate_message to see where to place the translation in the locale file.
In fact, you don't even need to provide the :message key if you follow the ActiveModel naming convention:
en:
activemodel:
errors:
models:
[your model name, e.g. user]:
attributes:
username:
taken: "username exists"
Do you set the locale in your application.rb ? Like :
config.i18n.default_locale = :en

Resources