One Month Rails - invalid email or password - ruby-on-rails

I took about a week off from working on "Mattan Griffel's One Month Rails." For some reason when I returned, either the password or the email was invalid for my localhost:3000. Mattan led us through the process of signing up on our localhost page with the email: user#example.com and password: foobar, but it won't work for me now. Could this be my fault with a syntax error in sublime, or what could be the problem?
This is what the Terminal reads when it doesn't go through:
Started POST "/users/sign_in" for 127.0.0.1 at 2013-06-06 13:53:44 -0600
Processing by Devise::SessionsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"8rUKRPLsIttdHhv49tgT8KcvKbjT9mMP/lP5M/N8uPQ=", "user"=>{"email"=>"user#example.com", "password"=>"[FILTERED]", "remember_me"=>"0"}, "commit"=>"Sign in"}
User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."email" = 'user#example.com' LIMIT 1

Given that this worked before, but it's not anymore, I'm guessing that you're probably just using the wrong password.
Try the following to reset your password in the Rails console:
User.find_by_email('user#example.com').update_attribute(:password, 'your_new_password')
Then, try logging back in and see what happens.

Related

Invalid authenticity token in Rails

Trying to sign in a user with Devise, I get an invalid authenticity token error.
I have csrf_meta_tags in my layout, and there is an authenticity_token present in the request params. As is suggested in answers to other questions, protect_from_forgery with: :exception is before before_action :authenticate_user!.
If I comment out protect_from_forgery, I see the following in my server log:
Started POST "/users/sign_in" for 127.0.0.1 at 2018-01-19 16:13:46 -0500
Processing by Devise::SessionsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"[TOKEN]", "user"=>{"badge_number"=>"0285", "password"=>"[FILTERED]"}, "commit"=>"Log in"}
User Load (0.3ms) SELECT `users`.* FROM `users` WHERE `users`.`badge_number` = '0285' ORDER BY `users`.`id` ASC LIMIT 1
(0.2ms) SELECT `divisions`.`id` FROM `divisions` INNER JOIN `divisions_users` ON `divisions`.`id` = `divisions_users`.`division_id` WHERE `divisions_users`.`user_id` = 2
CACHE (0.0ms) SELECT `divisions`.`id` FROM `divisions` INNER JOIN `divisions_users` ON `divisions`.`id` = `divisions_users`.`division_id` WHERE `divisions_users`.`user_id` = 2 [["user_id", 2]]
Redirected to http://localhost:3000/
Completed 302 Found in 141ms (ActiveRecord: 2.1ms)
Started GET "/" for 127.0.0.1 at 2018-01-19 16:13:46 -0500
Processing by IncidentsController#index as HTML
Completed 401 Unauthorized in 0ms (ActiveRecord: 0.0ms)
So it looks like the login is working, but then the redirect to the requested path (/) results in a 401 and being redirected to the login page, as if the login isn't working.
However none of this really explains why I'm getting the authenticity token error in the first place.
Not sure what the next step to investigate the problem might be, given that as far as I can see all the required elements for CSRF token verification are in place.
I fixed this by clearing my cookie for localhost.
I had used SSH tunneling via a localhost port to access the production site, so a cookie based on a conflicting session and secret_key_base was in the localhost domain.
I prevented this from occurring again by prepending the Rails environment to the name of the cookie:
Rails.application.config.session_store :cookie_store, key: "_incidents_#{Rails.env}_session"
So that despite using localhost to access my development and production environments, they would be writing to different cookies by virtue of being in different environments.
For Rails 5, note that protect_from_forgery is no longer prepended to
the before_action chain, so if you have set authenticate_user before
protect_from_forgery, your request will result in "Can't verify CSRF
token authenticity." [link]
To resolve this, either change the order in which you call them, or use :
protect_from_forgery with: :exception, prepend: true

devise goes crazy with accept headers of "*/*"

As an authenticated user, if I visit a url to my app via an external text editor, the mimetype shows up in the console as "*/*", and devise seems to redirect to "/sign_in" multiple times. This is a problem because if I go to "/foo", this is initially stored in the session as the path to return to after authentication. Due to the number of redirects, this value is blown away in the session and after devise finally realizes the user is already signed in, it ends up redirecting to "/".
For testing, I added to my application controller:
def authenticate_user!
puts "***** AUTHENTICATE USER CALLED!!!"
super
end
So, if I enter the url directly in my browser, the mimetype shows up as HTML, and it sees I am authenticated immediately and everything is rendered as expected:
Started GET "/products/171" for 127.0.0.1 at 2015-02-11 17:04:53 -0800
ActiveRecord::SchemaMigration Load (0.4ms) SELECT "schema_migrations".* FROM "schema_migrations"
Processing by LayoutsController#show as HTML
Parameters: {"id"=>"171"}
***** AUTHENTICATE USER CALLED!!!
User Load (0.9ms) SELECT "users".* FROM "users" WHERE "users"."id" = 7 ORDER BY "users"."id" ASC LIMIT 1
Rendered html template within layouts/application (0.1ms)
Completed 200 OK in 1165ms (Views: 1127.7ms | ActiveRecord: 3.0ms)
However, when I click a link in an external text editor, I get this crazy behavior:
Started GET "/products/171" for 127.0.0.1 at 2015-02-11 17:09:43 -0800
Processing by LayoutsController#show as */*
Parameters: {"id"=>"171"}
***** AUTHENTICATE USER!!!
Completed 401 Unauthorized in 4ms
I18N keys: [:en, :devise, :failure, :user, :unauthenticated]
I18N keys: [:en, :devise, :failure, :unauthenticated]
=> You need to sign in or sign up before continuing.
Started GET "/sign_in" for 127.0.0.1 at 2015-02-11 17:09:43 -0800
Processing by Devise::SessionsController#new as */*
I18N keys: [:en, :sign_in, :submit_button]
=> Sign in
I18N keys: [:en, :sign_in, :disabled]
=> Your account has been disabled.
Rendered devise/sessions/new.html.haml within layouts/sign_in (6.8ms)
Started GET "/sign_in" for 127.0.0.1 at 2015-02-11 17:09:45 -0800
Processing by Devise::SessionsController#new as HTML
User Load (0.5ms) SELECT "users".* FROM "users" WHERE "users"."id" = 7 ORDER BY "users"."id" ASC LIMIT 1
I18N keys: [:en, :devise, :failure, :already_authenticated]
=> You are already signed in.
Redirected to http://localhost:3000/
Filter chain halted as :require_no_authentication rendered or redirected
Completed 302 Found in 5ms (ActiveRecord: 0.5ms)
Started GET "/" for 127.0.0.1 at 2015-02-11 17:09:45 -0800
User Load (0.4ms) SELECT "users".* FROM "users" WHERE "users"."id" = 7 ORDER BY "users"."id" ASC LIMIT 1
Processing by LayoutsController#show as HTML
***** AUTHENTICATE USER!!!
Completed 200 OK in 244ms (Views: 178.8ms | ActiveRecord: 0.0ms)
Note the "Redirected to http://localhost:3000/" rather than http://localhost:3000/products/171, which is what should be happening.
Why does */* cause this behavior, and how can I fix this?
UPDATE
Apparently the problem is, I get a completely different sessions between visiting directly from the Chrome's url bar, and from clicking a link in an external text editor (even though the text editor is simply opening a new tab in chrome with that url):
from chrome after clicking link in external text editor:
request.cookies => {"_my_app_session"=>"f32dc5c239fadfc494a775990112f2b5"}
from putting url directly in chrome:
request.cookies => {"_my_app_session"=>"91ac136666b78499ea6e071f89cec7ee"}
How in the world is this possible? It's the same browser.. I thought all tabs in a browser have the same session and there's no way you can change that?
I figured out what is happening here... Microsoft Word is the "external editor" in question, and apparently it visits the url internally before kicking it off to your OS default browser. I guess they are spying on their users to see where they are going and what the response of the site is before sending to a browser. That's why the session is different...

Rails cucumber simple test, step redirect after login_as

I'm new with BDD approach and I'm studying to put that in all my future projects.
I'm trying to run a simple test in which the user has to be logged to access a specific page (the Create New Fair page) and fill a field form before submit.
It seems I was able to manage login since the test passed but when I try to access Fair page I'm always redirected to the welcome/index for some reason I don't understand. As result of this I receive a "Unable to find button "Create Fair" message in the next next.
Here my files to let you understand my problem:
fairs.feature:
Feature: Fairs
In order to create a new Fair
A user must be logged
Should fill fair form
Scenario: Create a new Fair
Given I'm logged as superuser
And I'm on the add Fair page
And I fill in "name"
When I press "Create Fair"
Then A new fair should be created with success
create_fair_steps.rb (only steps I've problem with):
Given(/^I'm logged as superuser$/) do
user = build(:user)
login_as(user, :scope => :user, :run_callbacks => false)
#Warden.test_reset!
end
Given(/^I'm on the add Fair page$/) do
visit('/it/fairs/new')
end
When(/^I press "(.*?)"$/) do |confirm_button|
#submit_form "new_fair"
click_button confirm_button
end
users.rb ()
FactoryGirl.define do
factory :user, class: User do
email "admin#email.com"
password "superadmin"
end
end
To use FactoryGirl i've added the following line to the env.rb file:
World(FactoryGirl::Syntax::Methods)
The output log
Feature: Fairs
In order to create a new Fair
A user must be logged
Should fill fair form
Scenario: Create a new Fair # features/fairs.feature:6
(0.1ms) begin transaction
(0.1ms) commit transaction
(0.1ms) begin transaction
Given I'm logged as superuser # features/step_definitions/create_fair_steps.rb:4
Started GET "/it/fairs/new" for 127.0.0.1 at 2014-07-31 17:50:42 +0200
Processing by FairsController#new as HTML
Parameters: {"locale"=>"it"}
Redirected to http://www.example.com/it
Completed 302 Found in 254ms (ActiveRecord: 0.4ms)
Started GET "/it" for 127.0.0.1 at 2014-07-31 17:50:42 +0200
User Load (0.6ms) SELECT "users".* FROM "users" WHERE "users"."id" IS NULL ORDER BY "users"."id" ASC LIMIT 1
Processing by WelcomeController#home as HTML
Parameters: {"locale"=>"it"}
Redirected to http://www.example.com/it/home
Completed 302 Found in 1ms (ActiveRecord: 0.0ms)
Started GET "/it/home" for 127.0.0.1 at 2014-07-31 17:50:42 +0200
Processing by WelcomeController#index as HTML
Parameters: {"locale"=>"it"}
Rendered welcome/index.html.erb within layouts/site (3.2ms)
Completed 200 OK in 314ms (Views: 298.8ms | ActiveRecord: 0.0ms)
And I'm on the add Fair page # features/step_definitions/create_fair_steps.rb:10
And I fill in "name" # features/step_definitions/create_fair_steps.rb:14
When I press "Create Fair" # features/step_definitions/create_fair_steps.rb:18
Unable to find button "Create Fair" (Capybara::ElementNotFound)
./features/step_definitions/create_fair_steps.rb:20:in `/^I press "(.*?)"$/'
features/fairs.feature:10:in `When I press "Create Fair"'
Then A new fair should be created with success # features/step_definitions/create_fair_steps.rb:23
(0.1ms) rollback transaction
Failing Scenarios:
cucumber features/fairs.feature:6 # Scenario: Create a new Fair
1 scenario (1 failed)
5 steps (1 failed, 1 skipped, 3 passed)
If you need more information let me know. Any help is appreciated, thanks :)

Password digest can't be blank

Ruby on Rails 3.2
My form is creating a new distributor. I have added the gem 'bcrypt-ruby', '3.0.1', my database table has password_digest: string and my model has :password, :password_confirmation, and has_secure_password.
When I submit my form the error I get is Password digest can't be blank.
This is what is POSTed:
Started POST "/distributors" for x.x.x.x at 2014-03-14 12:59:07 -0700
Processing by DistributorsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"x=", "distributor"=>{"company_name"=>"First Account", "company_website
"=>"First.com", "contact_name"=>"First", "contact_email"=>"first#moon.com", "contact_title"=>"owner", "company_phone"=>"555-665-5555", "company_region"=>"Asia Paci
fic", "company_address"=>"172 E Center Street", "company_country"=>"Cambodia", "company_city"=>"Covina", "company_state"=>"Not Applicable", "company_zip"=>"01970",
"sales_contact_name"=>"Bob", "sales_contact_email"=>"bobby#moon.com", "tech_contact_name"=>"Steph", "tech_contact_email"=>"steph#moon.com", "additional_name"=>"",
"additional_email"=>"", "additional_name2"=>"", "additional_email2"=>"", "area_served"=>["", "Bangladesh"], "terms_and_conditions"=>"1"}, "commit"=>"Register"}
Distributor Load (0.1ms) SELECT `distributors`.* FROM `distributors` WHERE `distributors`.`contact_email` = 'first#moon.com' LIMIT 1
(0.1ms) BEGIN
Distributor Exists (0.2ms) SELECT 1 AS one FROM `distributors` WHERE `distributors`.`contact_email` = 'first#moon.com' LIMIT 1
(0.1ms) ROLLBACK
Does someone know what I'm missing? Thank you
Your log is missing both the password and password_confirmation fields being set. It should look more like this
{"utf8"=>"✓", "authenticity_token"=>"dsdfhjdskhfsdfhjsdfhjsdfhjdsfhjsdfE=", "user"=>{"email"=>"email#provider.com", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}, "commit"=>"Register"}
The hash you post to your distributors route does not contain any information about a password. It is not possible to create a distributor without a password, with the code you have written. So the error message is perfectly correct.
You need to add a password and a password_confirmation field to your webpage.

Rails + Devise: When a user tries to sign in before confirming with the confirmation email, no error notice appears?

So I have a Rails app with Devise set up. I have :confirmable set up in my Users table, and sending confirmation emails works perfectly.
However, I'm running into a small issue with unconfirmed users trying to sign in.
When an invalid email/password combination are input into the login, I get a flash notice that says "Invalid email or password.". However, if an unconfirmed user signs in correctly, they are redirected back to /users/sign_in, but there is no flash message for "You have to confirm your account before continuing.", which is defined in /config/locales/devise.en.yml.
I have overridden thses methods:
RegistrationsController) :new, :create
SessionsController) :create
ConfirmationsController) :after_confirmation_path_for
What exactly does Devise do when an unconfirmed user signs in with the correct credentials? I tried putting a binding.pry statement at the top of my sessions#create method, but it never hits it, meaning Devise must have some sort of outside check for this. I've attempted to look at the source code to no avail.
This is what the log states is happening:
Started POST "/users/sign_in" for 127.0.0.1 at 2013-10-18 15:04:26 -0400
Processing by SessionsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"03kQgiMGyXcq/nW8jlVyGkGDw1Q9lpP+JZ03e+LZHPU=", "user"=>{"email"=>"dummy#example.com", "password"=>"[FILTERED]"}, "commit"=>"Login"}
[1m[35mUser Load (0.7ms)[0m SELECT `users`.* FROM `users` WHERE `users`.`email` = 'dummy#example.com' LIMIT 1
[1m[36m (0.2ms)[0m [1mBEGIN[0m
[1m[35m (0.1ms)[0m COMMIT
Completed 401 Unauthorized in 90ms
Started GET "/users/sign_in" for 127.0.0.1 at 2013-10-18 15:04:27 -0400
Processing by SessionsController#new as HTML
Rendered devise/shared/_links.haml (0.6ms)
Rendered devise/sessions/new.html.haml within layouts/application (5.0ms)
Rendered layouts/_header.html.haml (0.9ms)
Rendered layouts/_navigation.html.haml (0.6ms)
Rendered layouts/_footer.html.haml (0.9ms)
Completed 200 OK in 33ms (Views: 28.0ms | ActiveRecord: 0.0ms)
So it does look like the sessions#create method is being hit. So I'm not sure where to go from here. Any help would be appreciated!
config/routes.rb
devise_for :users, :controllers => {
:registrations => "registrations",
:sessions => "sessions",
:confirmations => "confirmations"}
Figured it out. When something in devise calls one of the message under :failures, it doesn't put the message in flash[:notice], it puts the message in flash[:alert], so I just needed to add
#alert= alert
to my haml.
Source: Always getting 401 Unauthorized with new install of Rails + Devise

Resources