rails app commits SQL transaction but no change in actual table - mysql

my rails app generates the following server queries
Processing by ResponsesController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"WJBM8CJQaLxkRfC3/cGimaEytM3EvqCWhOmfX1WBRQA=", "response"=>{"q_id"=>"4", "taker_id"=>"10", "value"=>"4", "text"=>"fsfsf"}, "commit"=>"Create Response", "locale"=>"en"}
Question Load (0.1ms) SELECT "questions".* FROM "questions" WHERE "questions"."id" = ? LIMIT 1 [["id", "4"]]
(0.1ms)
begin transaction
SQL (0.4ms) INSERT INTO "responses" ("created_at", "q_id", "taker_id", "text", "updated_at", "value") VALUES (?, ?, ?, ?, ?, ?) [["created_at", Fri, 11 Oct 2013 18:54:10 UTC +00:00], ["q_id", 4], ["taker_id", 10], ["text", "fsfsf"], ["updated_at", Fri, 11 Oct 2013 18:54:10 UTC +00:00], ["value", 4]]
(2.3ms) commit transaction
default_url_options is passed options: {}
However, there is no actual change I can see in my local mysql db (on macos)
mysql> use medisupply
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
Database changed
mysql> select * from responses
-> ;
Empty set (0,00 sec)
Any ideas what could be the reason for that? Its driving me insane.
my database.yml config:
development:
adapter: mysql
encoding: utf8
reconnect: false
host: localhost
database: medisupply
pool: 5
username: root
password:
socket: /tmp/mysql.sock
thanks heaps

Related

Rails invalid hash password authenticates in ruby console but after reopening it doesn't. Why?

I am following [lynda.com's Ruby on Rails 5 Essential Training][1] and am very stuck when building the login system.
The issue is the database seems to be holding a different hash to what rails is using. I have looked all over for reasons and fixes and I understand that the stored hash and the one rails runs are different but why and how can I fix this?
I have added:
bcrypt 3.1.11 gem installed password_digest column in table
has_secure_password to correct model file
I have migrated down and back up again to see if there are issues with the table.
The password stored in the database is hashed - password_digest: $2a$10$AMHXZBl/zXQ9yHOR7uBSiOdsGloArDkxO
I have even followed these steps in the Ruby console:
user.password = 'password'
user.password_confirmation = 'password'
user.save
user.authenticate('password')
The password saves and the authentication brings up the correct entry but it does not match after rerunning the console or using the login page on rails server.
I get this error each time:
BCrypt::Errors::InvalidHash (invalid hash):
app/controllers/cms_access_controller.rb:16:in `attempt_login'
and invalid hash error in the browser gets stuck here:
found_user = CmsUser.where(:username => params[:username]).first
if found_user
authorized_user = found_user.authenticate(params[:password])
end
end
Here is the log from rails:
Started POST "/cms_access/attempt_login" for 127.0.0.1 at 2018-01-02 17:59:18 +0800
Processing by CmsAccessController#attempt_login as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"YP2tiHyRfDhJhhuF+PPM0D+hA+6BMJW5YmTyZyLpT6nXs4NdhGyihVKZpoMaRl0oUsobnr6x5bYGBR75+huUjg==", "username"=>"username", "password"=>"[FILTERED]", "commit"=>"Login"}
[1m[36mCmsUser Load (0.4ms)[0m [1m[34mSELECT `cms_users`.* FROM `cms_users` WHERE `cms_users`.`username` = 'username' ORDER BY `cms_users`.`id` ASC LIMIT 1[0m
Completed 500 Internal Server Error in 9ms (ActiveRecord: 0.4ms)
BCrypt::Errors::InvalidHash (invalid hash):
app/controllers/cms_access_controller.rb:16:in `attempt_login'
Full irb code as follows:
irb(main):001:0> u = CmsUser.first
(0.4ms) SET NAMES utf8, ##SESSION.sql_mode = CONCAT(REPLACE(REPLACE(REPLACE(##sql_mode, 'STRICT_TRANS_TABLES', ''), 'STRICT_ALL_TABLES', ''), 'TRADITIONAL', ''), ',NO_AUTO_VALUE_ON_ZERO'), ##SESSION.sql_auto_is_null = 0, ##SESSION.wait_timeout = 2147483
CmsUser Load (0.2ms) SELECT `cms_users`.* FROM `cms_users` ORDER BY `cms_users`.`id` ASC LIMIT 1
=> #<CmsUser id: 1, first_name: "first name", last_name: "last name", email: "email", username: "username", password_digest: nil, created_at: "2018-01-02 14:48:42", updated_at: "2018-01-02 14:48:42">
irb(main):002:0> u.password = "password"
=> "password"
irb(main):003:0> u.password_confirmation = "password"
=> "password"
irb(main):004:0> u.save
(0.3ms) BEGIN
SQL (0.4ms) UPDATE `cms_users` SET `password_digest` = '$2a$10$gKAyDPTNzg.7Xnd7uatzuu0VWZNH6zGPA653RZ.5THB2Rziax1fyC', `updated_at` = '2018-01-02 14:50:29' WHERE `cms_users`.`id` = 1
(1.1ms) COMMIT
=> true
irb(main):005:0> u.authenticate("password")
=> #<CmsUser id: 1, first_name: "first name", last_name: "last name", email: "email", username: "username", password_digest: "$2a$10$gKAyDPTNzg.7Xnd7uatzuu0VWZNH6zGPA653RZ.5THB...", created_at: "2018-01-02 14:48:42", updated_at: "2018-01-02 14:50:29">
After running rails server and attempting login:
Started POST "/cms_access/attempt_login" for 127.0.0.1 at 2018-01-02 22:52:01 +0800
Processing by CmsAccessController#attempt_login as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"qF/U+46QhGZHYuEbfPTStRxryPpp0hIEt1TQIRVE5bgfEfoudm1a21x9XB2eQUNNcQDQilZTYgvTNTy/zbY+nw==", "username"=>"username", "password"=>"[FILTERED]", "commit"=>"Login"}
CmsUser Load (0.4ms) SELECT `cms_users`.* FROM `cms_users` WHERE `cms_users`.`username` = 'username' ORDER BY `cms_users`.`id` ASC LIMIT 1
Completed 500 Internal Server Error in 11ms (ActiveRecord: 0.8ms)
BCrypt::Errors::InvalidHash (invalid hash):
app/controllers/cms_access_controller.rb:16:in `attempt_login'
Try to following sign in action like below
found_user = CmsUser.find_by(:username => params[:session][:username].downcase)
if found_user && found_user.authenticate(params[:session][:password])
#=> code to be here
else
#=> code to be here
end
Hope to help

NodeJS: MySQL returns inaccurate decimal values

I've a MySQL database storing decimal values (DECIMAL(32, 12)).
When I select the values using HeidiSQL, the values are shown correctly (e.g. 15922.638440778302). But when I do the same in NodeJS using the MySQL binding (https://github.com/mysqljs/mysql), it shows me 15922.638440778303.
My SQL-Query is pretty simple:
SELECT SUM(`amount`) FROM `balances`;
Any idea what can cause the difference? Maybe do I need to specify the precision during the MySQL initialization in NodeJS? At the moment, I don't specify anything other than the login credentials:
let mysql = require('mysql').createPool({
host: global.dbconfig['dbhost'],
database: global.dbconfig['dbname'],
user: global.dbconfig['dbuser'],
password: global.dbconfig['dbpass']
})
Add below lines to your mysql config.
supportBigNumbers: true
bigNumberStrings: true
Then it becomes:
let mysql = require('mysql').createPool({
host: global.dbconfig['dbhost'],
database: global.dbconfig['dbname'],
user: global.dbconfig['dbuser'],
password: global.dbconfig['dbpass'],
supportBigNumbers: true,
bigNumberStrings: true,
})
More info on connection options: docs

Ruby on rails login error when installing Jackhammer

I am trying to install Jackhammer vulnerability tool on my Ubuntu 16.04.3 LTS. More details of the tool can be found here https://github.com/olacabs/jackhammer and the user guide is https://jch.olacabs.com/userguide/
I am running Jackhammer locally using rails method, but i am not able to login using the default credentials i.e.,
Username: jackhammer#olacabs.com
, password: j4ckh4mm3r
I have done the DB installation and configured mysql as shown below.I have also taken care of all the gems and dependencies.
default: &default
adapter: mysql2
encoding: utf8
pool: 25
port: 3306
username: root
password: pass
host: localhost
socket: /var/run/mysqld/mysqld.sock
development:
<<: *default
database: jackhammer_development
test:
<<: *default
database: jackhammer_test
production:
<<: *default
database: jackhammer_production
After doing all the required installation i ran the command
bin/rake db:migrate RAILS_ENV=production
also
bin/rake db:migrate RAILS_ENV=development
separately but still same issue.
I have created databases in mysql as well.
mysql> show databases;
+------------------------+
| Database |
+------------------------+
| information_schema |
| jackhammer_development |
| jackhammer_production |
| jackhammer_test |
| mysql |
| performance_schema |
| sys |
+------------------------+
7 rows in set (0,00 sec)
Then finally this,
rails s
=> Booting Puma
=> Rails 4.2.7.1 application starting in development on http://localhost:3000
=> Run `rails server -h` for more startup options
=> Ctrl-C to shutdown server
Puma 2.14.0 starting...
* Min threads: 0, max threads: 16
* Environment: development
* Listening on tcp://localhost:3000
Now when i enter the default credentials or try to register i am not able to login, below is the development.log result..
I, [2017-11-03T10:45:16.824262 #5598] INFO -- : Started POST "/users/sign_in" for 127.0.0.1 at 2017-11-03 10:45:16 +0100
I, [2017-11-03T10:45:16.831569 #5598] INFO -- : Processing by Devise::SessionsController#create as HTML
I, [2017-11-03T10:45:16.831674 #5598] INFO -- : Parameters: {"utf8"=>"✓", "authenticity_token"=>"A/7MsxMp6f32zN2sbZKlTSCH23GYoYK+Wci24Lri1/a33EYOVUGYDq14Rkx2cL25iMb/6ff1BJRLKeMycQpe5Q==", "user"=>{"email"=>"jackhammer#olacabs.com", "password"=>"[FILTERED]"}, "commit"=>"LOGIN"}
D, [2017-11-03T10:45:16.835452 #5598] DEBUG -- : [1m[36mUser Load (0.4ms)[0m [1mSELECT `users`.* FROM `users` WHERE `users`.`email` = 'jackhammer#olacabs.com' ORDER BY `users`.`id` ASC LIMIT 1[0m
I, [2017-11-03T10:45:16.835800 #5598] INFO -- : Completed 401 Unauthorized in 4ms (ActiveRecord: 0.9ms)
I, [2017-11-03T10:45:16.836908 #5598] INFO -- : Processing by Devise::SessionsController#new as HTML
I, [2017-11-03T10:45:16.837000 #5598] INFO -- : Parameters: {"utf8"=>"✓", "authenticity_token"=>"A/7MsxMp6f32zN2sbZKlTSCH23GYoYK+Wci24Lri1/a33EYOVUGYDq14Rkx2cL25iMb/6ff1BJRLKeMycQpe5Q==", "user"=>{"email"=>"jackhammer#olacabs.com", "password"=>"[FILTERED]"}, "commit"=>"LOGIN"}
I, [2017-11-03T10:45:16.980094 #5598] INFO -- : Rendered users/sessions/new.html.erb within layouts/application (1.5ms)
I, [2017-11-03T10:45:17.477418 #5598] INFO -- : Completed 200 OK in 640ms (Views: 500.2ms | ActiveRecord: 0.0ms)
D, [2017-11-03T10:45:55.746744 #5598] DEBUG -- :
D, [2017-11-03T10:45:55.746873 #5598] DEBUG -- :
I, [2017-11-03T10:45:55.747045 #5598] INFO -- : Started GET "/users/sign_up" for 127.0.0.1 at 2017-11-03 10:45:55 +0100
I, [2017-11-03T10:45:55.780581 #5598] INFO -- : Processing by Users::RegistrationsController#new as HTML
D, [2017-11-03T10:45:55.810327 #5598] DEBUG -- : [1m[36mTeam Load (0.4ms)[0m [1mSELECT `teams`.* FROM `teams` ORDER BY `teams`.`name` ASC[0m
I, [2017-11-03T10:45:55.848704 #5598] INFO -- : Rendered users/registrations/new.html.erb within layouts/application (55.1ms)
I, [2017-11-03T10:45:56.328669 #5598] INFO -- : Completed 200 OK in 548ms (Views: 542.3ms | ActiveRecord: 2.4ms)
I am really stuck and don't no how to proceed further. Any kind of help is really appreciated.
Thanks in advance.
What you have done so far is to only create the initial empty database (rake db:migrate).
You also need to run rake db:seed to load the seed data for the database:
https://github.com/olacabs/jackhammer/blob/master/web/app/db/seeds.rb

RubyOnRails multiple database connections errors

I have a rails application (ruby 2.0.0, Rails 4.0.1) that connects to several MySQL database.
The connection to the local database always work properly, this is my configuration:
production:
adapter: mysql
encoding: utf8
database: xxx
username: yyy
password: zzz
host: x.x.x.x
port: 3306
reconnect: true
But connections to remote databases often return an error, such as connecting to my radius external database returns the following error:
Mysql :: Error:: SELECT 1 AS one FROM WHERE `` radacct` radacct`.`username` =? LIMIT 1
Updating the page several times, the connection is restored and I can see the data properly. This is my configuration:
radius:
port: 3306
adapter: mysql
encoding: utf8
database: xxx
username: yyy
password: zzz
host: x.x.x.x
reconnect: true
connect_timeout: 60
read_timeout: 90
write_timeout: 90
checkout_timeout: 10
reaping_frequency: 30
dead_connection_timeout: 30
I tried to change the configuration of the timers in different ways, but the problem persists.
to connect to the radius server I created the following model common to all:
class RadActiveRecord <ActiveRecord :: Base
self.abstract_class = true
establish_connection "radius"
end
for example for the table radacct use the following model:
class RadAcctDetail <RadActiveRecord
self.table_name = "radacct"
end
the error in question is with any queries, such as:
def index
#rad_acct_details = RadAcctDetail.all.paginate = (
: order => "radacctid DESC"
: page => params [: page] || 1
: per_page => params [: per_page] || 25)
end
Does anyone have any suggestions?

Check mysql connection to remote host

I have model to store database connection parameters (host, database name, username, password) and filling it by form. Before create or update I need to check if connection be good with entered parameters. I create validate :check_connection validator:
# don`t change primary connection
class Remote < ActiveRecord::Base; end
def check_connection
return if errors.any? || (!new_record? && password.empty?)
begin
Remote.establish_connection(
adapter: 'mysql2',
host: host,
username: username,
password: password,
database: database,
connect_timeout: 5,
reconnect: false
)
# maybe need to make some sql request? did try it
rescue Exception => e
errors.add :connection, 'Could not connect to database'
end
end
When I try enter accessible host (localhost), code like above works good. But if host like 192.168.1.1 (unaccessible) page freezing after submit form. I see attempts to connect every second and it did not stop after ESC (stop loading page) at browser (I see attempts at tcpdump on network interface). And attempts did not stop..
So, how can I validate connection to database? And if connection can not be established page must will not be load long time.
I did use gem 'mysql2' and bundle install 0.3.11 version. This version ignore connect_timeout and bug fixed at newer version. After I try 0.3.12b4 (gem 'mysql2', '~> 0.3.12b4') all works fine.
Variable connect_timeout is a global variable. Therefore, mysql2 maybe ignore it.
on mysql5.6:
mysql[(none)]> set connect_timeout = 123;
ERROR 1229 (HY000): Variable 'connect_timeout' is a GLOBAL variable and should be set with SET GLOBAL
I set timeout variables when initializing mysql2 but it's not reflected. A README of mysql2 says that you can set the *timeout options, but I think the README is outdated or broken.
on mysql2 0.3.14(gem):
client = Mysql2::Client.new(
host: 'localhost',
database: 'test',
username: 'root',
password: '',
connect_timeout: 3,
read_timeout: 3,
write_timeout: 3,
wait_timeout: 3);
client.query('show variables like "%timeout%"').map{|r| [r["Variable_name"], r["Value"]] }
=> [["connect_timeout", "10"],
["delayed_insert_timeout", "300"],
["innodb_lock_wait_timeout", "50"],
["innodb_rollback_on_timeout", "OFF"],
["interactive_timeout", "28800"],
["lock_wait_timeout", "31536000"],
["net_read_timeout", "30"], # Maybe older mysql has read_timeout?
["net_write_timeout", "60"], # Maybe older mysql has write_timeout?
["slave_net_timeout", "3600"],
["wait_timeout", "28800"]]
If you use ActiveRecord, you can set only wait_timeout variable by database.yml.
in database.yml:
development:
adapter: mysql2
encoding: utf8
charset: utf8
database: test
pool: 5
username: root
password:
host: localhost
connect_timeout: 3
read_timeout: 3
write_timeout: 3
wait_timeout: 3
A result of ActiveRecord 4.0.1:
> ActiveRecord::Base.connection.execute('show variables like "%timeout%"').to_a
=> [["connect_timeout", "10"],
["delayed_insert_timeout", "300"],
["innodb_flush_log_at_timeout", "1"],
["innodb_lock_wait_timeout", "50"],
["innodb_rollback_on_timeout", "OFF"],
["interactive_timeout", "28800"],
["lock_wait_timeout", "31536000"],
["net_read_timeout", "30"],
["net_write_timeout", "60"],
["rpl_stop_slave_timeout", "31536000"],
["slave_net_timeout", "3600"],
["wait_timeout", "3"]]
ActiveRecord set wait_timeout variable in abstract_mysql_adapter.rb.
see:
abstract_mysql_adapter.rb
https://github.com/rails/rails/blob/master/activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb
mysql2_adapter.rb
https://github.com/rails/rails/blob/master/activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb