Devise Password Reset Issue Rails 4 - ruby-on-rails

I'm using Devise for authentication with a Rails 4 app and am having issues with the password reset. Locally, everything works fine, when I paste the reset link in (i.e. localhost:3000/users/password/edit?reset_password_token=e_f3ZpqrE_rTBZmKJk_E) it works as expected.
On Heroku however, Devise seems to not even notice the :reset_password_token param, and automatically redirect to /users/signin with the notice "You can't access this page without coming from a password reset email. If you do come from a password reset email, please make sure you used the full URL provided."
Here's is an example of the link that is being generated: http://mysite.io/users/password/edit?reset_password_token=anzYNreZEcz4-dtZy5Uf
I even overrode the assert_reset_token_passed method in my own controller to check if params[:reset_password_token] was actually blank, and for some reason it is, rails is not pulling this out of the url. Here's my modified method:
def assert_reset_token_passed
logger.info params[:reset_password_token] #This is blank somehow
if params[:reset_password_token].blank?
set_flash_message(:alert, :no_token)
redirect_to new_session_path(resource_name) #This is where the redirect happens
end
end
Any help would be much appreciated.

I was having the exact same issue. The fix for me was to update the config.action_mailer.default_url_options in production.rb to include the full host (in my case 'www.mydomain.com' vs 'mydomain.com').
To clarify, it used to be
config.action_mailer.default_url_options = { :host => 'mydomain.com' }
and now it's
config.action_mailer.default_url_options = { :host => 'www.mydomain.com' }

Related

Create issue on production but not on localhost

On my rails application, I am receiving an error on production(heroku) but not on my localhost. All of my migrations are done and I can add it through the console, but I cannot get this to work in the controller.
So the area where the error is occuring is here:
respond_to do |format|
if #registration.save
EventMailer.new_registration_notification(#registration, #current_event).deliver
Recipient.create :first_name => #registration.first_name, :last_name => #registration.last_name, :email => #registration.email, :netID => #registration.netID, :event_id => #registration.event_id, :mailing_id => nil
format.html { redirect_to event_path(#current_event), notice: 'Registration was successful' }
Again, I am not getting an error in my development local environment but I am in production. They are both using Postgres. So my registrations ARE saving but Recipient is never created and I get an error. I've checked the heroku logs by running:
herkou logs
but there are no errors shown. On the front end, you see an error that says "Something went wrong. If you're the application owner please check your logs".
Fixed my problem, the problem was with sending the mailer. I did not notice that the mailer wasn't sending and just assumed it was an issue creating the Recipient. I needed to fix some configurations in the production.rb file to use the SMTP server. After fixing that the issue went away

Rails Tutorial, Hartl - ch. 10 - password/activate - Email link not redirecting to Heroku Site

The links that are sent in the password reset and account activation are being sent in the email, but when I click on them, they are not being redirected to my Heroku app and the browser gets stuck at "about:blank". Am I missing something? They look like this:
Reset password
Here is my app/views/user_mailer/password_reset.html.erb
<h1>Password reset</h1>
<p>To reset your password click the link below:</p>
<%= link_to "Reset password", edit_password_reset_url(#user.reset_token,
email: #user.email) %>
<p>This link will expire in two hours.</p>
<p>
If you did not request your password to be reset, please ignore this email and
your password will stay as it is.
</p>
Looks like the URL that you pass over to SendGrid is http://<your+heroku+app>.herokuapp.com/password_resets/..., so you'd need to make sure you specify your app's name instead of having http://<your+heroku+app>. If you're using SMTP, check to see if you have your config.action_mailer.default_url_options (in config/production.rb) setup properly:
config.action_mailer.default_url_options = { :host => 'http://appname.herokuapp.com' }
did same error and felt so LOL when I realized the solution:
check your config/environments/production.rb Listing 10.56
update host = '<your+heroku+app>.herokuapp.com' with your APP's name (in my case was host = 'twitterdave.herokuapp.com' )
Let me know if it helps

Devise "Confirmation token is invalid" when user signs up

Using Rails 4 and Devise 3.1.0 on my web app. I wrote a Cucumber test to test user sign up; it fails when the "confirm my account" link is clicked from the e-mail.
Scenario: User signs up with valid data # features/users/sign_up.feature:9
When I sign up with valid user data # features/step_definitions/user_steps.rb:87
Then I should receive an email # features/step_definitions/email_steps.rb:51
When I open the email # features/step_definitions/email_steps.rb:76
Then I should see the email delivered from "no-reply#mysite.com" # features/step_definitions/email_steps.rb:116
And I should see "You can confirm your account email through the link below:" in the email body # features/step_definitions/email_steps.rb:108
When I follow "Confirm my account" in the email # features/step_definitions/email_steps.rb:178
Then I should be signed in # features/step_definitions/user_steps.rb:142
expected to find text "Logout" in "...Confirmation token is invalid..." (RSpec::Expectations::ExpectationNotMetError)
./features/step_definitions/user_steps.rb:143:in `/^I should be signed in$
This error is reproducible when I sign up manually through the web server as well, so it doesn't appear to be a Cucumber issue.
I would like:
The user to be able to one-click confirm their account through this e-mail's link
Have the user stay signed in after confirming their account
I have setup:
The latest Devise code, from GitHub (3.1.0, ref 041fcf90807df5efded5fdcd53ced80544e7430f)
A User class that implements confirmable
Using the 'default' confirmation controller (I have not defined my own custom one.)
I have read these posts:
Devise confirmation_token is invalid
Devise 3.1: Now with more secure defaults
GitHub Issue - Devise confirmation_token invalid
And have tried:
Setting config.allow_insecure_tokens_lookup = true in my Devise initializer, which throws an 'unknown method' error on startup. Plus it sounds like this is only supposed to be a temporary fix, so I'd like to avoid using it.
Purged my DB and started from scratch (so no old tokens are present)
Update:
Checking the confirmation token stored on the User after registering. The emails token matches the DBs token. According to the posts above, the new Devise behavior says not supposed to, and that instead it is should generate a second token based on the e-mail's token. This is suspicious. Running User.confirm_by_token('[EMAIL_CONFIRMATION_TOKEN]') returns a User who has errors set "#messages={:confirmation_token=>["is invalid"]}", which appears to be the source of the issue.
Mismatching tokens seems to be the heart of the issue; running the following code in console to manually change the User's confirmation_token causes confirmation to succeed:
new_token = Devise.token_generator.digest(User, :confirmation_token, '[EMAIL_TOKEN]')
u = User.first
u.confirmation_token = new_token
u.save
User.confirm_by_token('[EMAIL_TOKEN]') # Succeeds
So why is it saving the wrong confirmation token to the DB in the first place? I am using a custom registration controller... maybe there's something in it that causes it to be set incorrectly?
routes.rb
devise_for :users,
:path => '',
:path_names => {
:sign_in => 'login',
:sign_out => 'logout',
:sign_up => 'register'
},
:controllers => {
:registrations => "users/registrations",
:sessions => "users/sessions"
}
users/registrations_controller.rb:
class Users::RegistrationsController < Devise::RegistrationsController
def create
# Custom code to fix DateTime issue
Utils::convert_params_date_select params[:user][:profile_attributes], :birthday, nil, true
super
end
def sign_up_params
# TODO: Still need to fix this. Strong parameters with nested attributes not working.
# Permitting all is a security hazard.
params.require(:user).permit!
#params.require(:user).permit(:email, :password, :password_confirmation, :profile_attributes)
end
private :sign_up_params
end
So upgrading to Devise 3.1.0 left some 'cruft' in a view that I hadn't touched in a while.
According to this blog post, you need to change your Devise mailer to use #token instead of the old #resource.confirmation_token.
Find this in app/views/<user>/mailer/confirmation_instructions.html.erb and change it to something like:
<p>Welcome <%= #resource.email %>!</p>
<p>You can confirm your account email through the link below:</p>
<p><%= link_to 'Confirm my account', confirmation_url(#resource, :confirmation_token => #token) %></p>
This should fix any token-based confirmation problems you're having. This is likely to fix any unlock or reset password token problems as well.
A friend of mine just found this question and emailed me asking if I had figured this out, which reminded me that I never submitted my own answer, so here goes :)
I ended up resetting the token & using send to get the raw token. It's ugly, but it works in a punch for devise (3.5.1).
26 it "should auto create org" do
27 email = FG.generate :email
28 visit new_user_registration_path
29 fill_in :user_name, with: 'Ryan Angilly'
30 fill_in :user_user_provided_email, with: email
31 fill_in :user_password, with: '1234567890'
32
33 expect do
34 click_button 'Continue'
35 end.to change { Organization.count }.by(1)
36
37 expect(page.current_path).to eq(confirmation_required_path)
38 u = User.where(email: email).first
39 u.send :generate_confirmation_token
40 email_token = u.instance_variable_get(:#raw_confirmation_token)
41 u.save!
42 os = u.organizations
43 expect(os.size).to eq(1)
44 visit user_confirmation_path(confirmation_token: email_token)
45 o = os.first
46
47 u.reload
48 expect(u.confirmed?)
49 expect(page.current_url).to eq(organization_getting_started_url(o))
50 end
As of devise 3.5.2, the confirmation token is no longer digested during the confirmation process. This means that the token in the email will match the token in the database.
I was still having trouble with confirmations after figuring this out, but in my case it turned out to be a bug I introduced when I overrode find_first_by_auth_conditions. By fixing the bug I introduced in that method, I fixed my errors with confirmation.

Problems With Resetting Password - Devise

I'm having problems when resetting a password using Devise.
When I click on 'Send me reset password instructions', I get:
ArgumentError at /users/password
Missing host to link to! Please provide the :host parameter, set default_url_options[:host], or set :only_path to true
It says that the problem is in /views/devise/mailer/reset_password_instructions.html.erb on line 5.
On line 5 in that file there is:
<p><%= link_to 'Change my password', edit_password_url(#resource, :reset_password_token => #resource.reset_password_token) %></p>
I have no idea how to setup a mailer in Rails although I have tried to. Can anybody help me with this?
Finally, you need to set up default url options for the mailer in each
environment. Here is the configuration for "config/environments/development.rb":
config.action_mailer.default_url_options = { :host => 'localhost:3000' }
You need to specify the host so it can be shown in the confimation email.
You can create a default filter like this:
# application_controller.rb
before_filter :mailer_set_url_options
...
def mailer_set_url_options
ActionMailer::Base.default_url_options[:host] = request.host_with_port
end

Lost values after switching email sending from AR_Mailer to DelayedJob

I've been using AR_Mailer for about 6 months without ever running into problems. I recently added DelayedJob for some administrative background jobs. Since DelayedJob also handles emails very well (thanks to DelayedMailer gem) I completely removed AR_Mailer from my application.
Everything works perfectly except this email. The password that is generated automatically is now lost.
#app/models/notifier.rb
def activation_instructions(user)
from default_email
#bcc = BACK_UP
#subject = "Activation instructions"
recipients user.email
sent_on Time.now
body :root_url => root_url, :user => user
end
#app/views/notifier/activation_instructions.erb
Thanks for signing up.
Your password is <%=#user.password-%>. For security reasons please change this on your first connection.
[....]
Any idea on why this bug occurs?
Thanks!
Configuration: Rails 2.3.2 & DelayedJob 2.0.4
I found out where the problem was. I looked in the database at the entry created in the delayed_jobs table:
--- !ruby/struct:Delayed::PerformableMethod
object: LOAD;Notifier
method: :deliver_activation_instructions!
args:
- LOAD;User;589
The user parameter is reloaded from the database by delayed_job before sending the email. In that case, the password is lost because it's not stored in the database.
So I've updated the code in order to pass explicitly the password:
#app/models/notifier.rb
def activation_instructions(user, password)
from default_email
#bcc = BACK_UP
#subject = "Activation instructions"
recipients user.email
sent_on Time.now
body :root_url => root_url, :user => user, :password => password
end
#app/views/notifier/activation_instructions.erb
Thanks for signing up.
Your password is <%=#password-%>. For security reasons please change this on your first connection.
[....]
Hope this helps other too!

Resources