Lost values after switching email sending from AR_Mailer to DelayedJob - ruby-on-rails

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!

Related

Devise Password Reset Issue Rails 4

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' }

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.

Cucumber devise sign in step failing (rails 3.2, cucumber, capybara, rspec)

Everytime i run the default devise user_step test " sign in" it fails.
Strange thing is the error i get
Scenario: User signs in successfully # features/users/sign_in.feature:12
Given I exist as a user # features/step_definitions/user_steps.rb:58
And I am not logged in # features/step_definitions/user_steps.rb:49
When I sign in with valid credentials # features/step_definitions/user_steps.rb:72
Then show me the page # features/step_definitions/user_steps.rb:152
And I see a successful sign in message # features/step_definitions/user_steps.rb:156
expected to find text "Signed in successfully." in "Mywebsite Follow us How it works More Login × **Invalid email or password**. Login * Email Password Remember me Not a member yet? Sign Up Now!Forgot your password?Didn't receive confirmation instructions? Rails Tutorial " (RSpec::Expectations::ExpectationNotMetError)
./features/step_definitions/user_steps.rb:157:in `/^I see a successful sign in message$/'
features/users/sign_in.feature:17:in `And I see a successful sign in message'
As you see capybara/cucumber tries to connect but gets "Invalid email or password"
So I used a trick seen on SO and added to see what capybara really was getting
Then /^show me the page$/ do
save_and_open_page
end
It tries to use the credentials I put on top of my file user_steps.rb:
def create_visitor
#visitor ||= { :name => "Testy McUserton", :email => "example#example.com",
:password => "please", :password_confirmation => "please" }
end
But it gets me "invalid (i can see example#example.com written in the email field on the capyabra page so it understands that i want this to be the email.
I'm lost. Why doesn't it work ?
You need to create the user in the database first. User.create(name: "Testy McUserton", email: "example#example.com", password: "please", :password_confirmation: "please"). Then you can login with the credentials. You can also use factorygirl link

sendmail_setting for hostingrails

Good afternoon,
I'm facing a problem about the way to send email through my application hosted on hostingrails.
In my config/initializers I added a file "setup_mailer" containing this
ActionMailer::Base.delivery_method = :sendmail
ActionMailer::Base.perform_deliveries = true
ActionMailer::Base.raise_delivery_errors = true
ActionMailer::Base.default_charset = "utf-8"
# Production
if Rails.env.production?
ActionMailer::Base.sendmail_settings = {
:location => '/usr/sbin/sendmail',
:arguments => '-i -t -f support#xxxxx.xxx'
}
end
and my mailer is as below
class Notification < ActionMailer::Base
def subscription_confirmation(user)
setup_email(user)
mail(:to => #recipients, :subject => "blabla")
end
protected
def setup_email(user)
#recipients = user.email
#from = "support#xxxxx.xx"
headers "Reply-to" => "support#xxxxx.xx"
#sent_on = Time.now
#content_type = "text/html"
end
end
It seems to work very fine on my local machine. But in production, emails are not sent properly and I receive this message in my support inbox.
A message that you sent using the -t command line option contained no
addresses that were not also on the command line, and were therefore
suppressed. This left no recipient addresses, and so no delivery could
be attempted.
If you have any idea, the support seems cannot help me, hope some of you'll have ideas or config files from hostingrails to share.
Thank you,
albandiguer
I had exactly the same problem - resolved it by removing the -t from the sendmail_settings.
I haven't looked much further to investigate other implications, but at least it works. But from the man page:
-t Extract recipients from message headers. These are added to any
recipients specified on the command line.
With Postfix versions prior to 2.1, this option requires that no
recipient addresses are specified on the command line.
So maybe just a difference in Postfix versions?
Try calling to_s on user.email or specifying user email as "#{user.email}"

how to raise/rescue from ActionMailer deliver method

I am sending emails with the following method:
class Communicate < ActionMailer::Base
def message(sub,msg,people)
subject sub
bcc people
from 'my_email.s#gmail.com'
sent_on Time.now
body :greeting => msg
end
end
bcc contains 4 or 5 email addresses.
During my testing I've noticed two things:
That if even one of the emails is not an actual email (for example fake_email_no_domain) it does not send emails to any of the recipients
if the bcc list has a bad email address (for example nonexistent#gmail.com) then it still sends emails to other recipients but still throws an error to the logs.
In both scenarios the error that is thrown is:
Redirected to http://localhost:3000/
Completed in 2601ms (DB: 1) | 302 Found [http://localhost/notifications]
[2010-08-04 00:49:00] ERROR Errno::ECONNRESET: Connection reset by peer
/usr/local/lib/ruby/1.9.1/webrick/httpserver.rb:56:in `eof?'
/usr/local/lib/ruby/1.9.1/webrick/httpserver.rb:56:in `run'
/usr/local/lib/ruby/1.9.1/webrick/server.rb:183:in `block in start_thread'
Questions:
Is there any way I can catch this error? I am showing a flash[:notice] to the user and i'd like to mention that something bad happened
If my BCC list has 5 emails and really only 4 emails are sent because 5th was nonexistent email then after all is done can I get a number of how many emails were actually sent? I'd like to show that number in my flash[:notice]. I can get this number by actually calling the delivery method in a iteration rather then sending as bulk but still I would not want to increment the count if one email is not sent.
Add or uncomment following line in the config/environments/development.rb and restart your server.
# Don't care if the mailer can't send
config.action_mailer.raise_delivery_errors = false
I assume you check for the development for production add line in config/environments/production.rb
If I am writing the code to sent the email in controller i can write like these to handle the rescue in my application
I'm using something like this in the controller:
if #user.save
begin
UserMailer.welcome_email(#user).deliver
flash[:success] = "#{#user.name} created"
rescue Net::SMTPAuthenticationError, Net::SMTPServerBusy, Net::SMTPSyntaxError, Net::SMTPFatalError, Net::SMTPUnknownError => e
flash[:success] = "User #{#user.name} creating Problems sending mail"
end
redirect_to home_index_path
end

Resources