Home arrow Ruby-on-Rails arrow Passwords and More Security for a Rails Ecommerce Application

Passwords and More Security for a Rails Ecommerce Application

In this third part to a four-part series on building the security into a Ruby-on-Rails ecommerce application, we'll focus on the changes we need to make to the program so that users can change their passwords. This article is excerpted from chapter eight of the book Practical Rails Projects, written by Eldon Alameda (Apress; ISBN: 1590597818).

Author Info:
By: Apress Publishing
Rating: 5 stars5 stars5 stars5 stars5 stars / 2
June 18, 2010
  1. · Passwords and More Security for a Rails Ecommerce Application
  2. · Updating the User Model
  3. · Using Observers
  4. · Modifying the Controller

print this article

Passwords and More Security for a Rails Ecommerce Application
(Page 1 of 4 )

Implementing the Reset Password User Story

To implement the third user story, Reset Password, we need a way to send e-mail messages from our application. The acts_as_authenticatedplugin comes with a generator for this, too. Execute the following command:

$ script/generate authenticated_mailer user

--------------------------------------------  exists  app/models/
  create  app/views/user_notifier
  exists  test/unit/
  create  app/models/user_notifier.rb
  create  app/models/user_observer.rb
  create  test/unit/user_notifier_test.rb 
  create app/views/user_notifier/activation.rhtml 
  create app/views/user_notifier/signup_notification.rhtml

There are two interesting things created by thegenerate authenticated_mailercommand:UserNotifier(an ActionMailer object) andUserObserver(an observer). Even though neither of them is a normal ActiveRecord model, they both reside in theapp/modelsdirectory. Weíll cover the mailer part now and talk about observers after we update theUsermodel.

Using ActionMailer Mailers

Rails has a specific package for sending (and receiving, which we donít need in this chapter) e-mail called ActionMailer. ActionMailer mailers are Rails classes stored inapp/modelsjust like normal ActiveRecord models, but they work quite differently.

TheUserNotifier mailer class we just created inapp/models/user_notifier.rblooks like this:

class UserNotifier < ActionMailer::Base
def signup_notification(user)
    @subject    += 'Please activate your new account'
    @body[:url]  = http://YOURSITE/account/activate/#{user.activation_code}

  def activation(user)
    @subject    += 'Your account has been activated!'
    @body[:url]  = http://YOURSITE/

def setup_email(user)
    @recipients  = "#{user.email}"
    @from        = "ADMINEMAIL"
    @subject     = "[YOURSITE] "
    @sent_on     = Time.now
    @body[:user] = user

Here,signup_notificationandactivationrepresent two different e-mail messages sent by the class. The former is sent when a new user has registered and must activate her account, and the latter is sent when the activation is complete. They both use the protectedsetup_emailmethod to prepare common header attributes of the e-mail, such asrecipients,from, andsubject. You can also set attributes for the message body, such as@body[:url]and@body[:user]. They will be available as instance variables in the e-mail templates.

We donít need the two mail methods that exist in the mailer, so we delete them and add our own method, as follows:

class UserNotifier < ActionMailer::Base
@@session = ActionController::Integration::Session.new

  def forgot_password(user)
@subject += "Password reset"
@body[:url] = @@session.url_for(:controller => "account",
:action => "reset_password",
                          :id => user.pw_reset_code, :only_path => false)

  def setup_email(user)
    @recipients  = "#{user.email}"
@from        = admin@emporium-books.com
    @subject     = "[Emporium] "
@sent_on     = Time.now
    @body[:user] = user

forgot_passwordis the mail method we deliver when George or someone from his staff requests a password reset. In the method, we set the subject for the mail, as well as define the password-reset URL sent in the e-mail message. Note that asurl_foris an instance method forActionController controllers, we canít call it directly from inside a mailer. However, with the trickery on the first line, we create a newActionController::Integration::Sessionobject through which we can callurl_for, and store it in a class variable, which can be used everywhere inside our mailer class. We also change thesetup_emailmethod a bit, to accommodate our application.

Next, we need to create a template for the mail body. Create a new template calledforgot_password.rhtmlinapp/views/user_notifierand put the following code in it:

Dear <%= @user.login %>,

Click the following link to reset your password at Emporium:
<%= @url %>

As you can see, the@bodyhash contents from the mailer method have been extracted to instance variables in the template, so that, for example,@body[:user]became@userand@body[:url]became@url.

Now that we have a mailer class and template ready, we can deliver a password-reset e-mail message by callingUserNotifier.deliver_forgot_password(@user_object). Rails will automatically retrieve the mailer method name after thedeliver_part in the method call, and deliver the mail prepared by that method.

Tip  If you want to delay the delivery of the e-mail (for example, because you have a mail sweeper that takes care of the deliveries), you can usecreate_instead ofdeliver_in the method call, and you will get aTMail object in return. For more information aboutTMail, seehttp://i.loveruby.net/en/projects/tmail.

blog comments powered by Disqus

- Ruby-on-Rails Faces Second Security Flaw in ...
- Ruby 2.0 Prepped for February 2013 Release
- Why LinkedIn Switched from Ruby on Rails
- Adding Style with Action Pack
- Handling HTML in Templates with Action Pack
- Filters, Controllers and Helpers in Action P...
- Action Pack and Controller Filters
- Action Pack Categories and Events
- Logging Out, Events and Templates with Actio...
- Action Pack Sessions and Architecture
- More on Action Pack Partial Templates
- Action Pack Partial Templates
- Displaying Error Messages with the Action Pa...
- Action Pack Request Parameters
- Creating an Action Pack Registration Form

Watch our Tech Videos 
Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us 
Weekly Newsletter
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 

Developer Shed Affiliates


© 2003-2019 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials