In this conclusion to a four-part series covering security for a Ruby on Rails ecommerce application, you'll learn how to protect the application against SQL injection, cross-site request forgery, and more. This article is excerpted from chapter eight of the book Practical Rails Projects, written by Eldon Alameda (Apress; ISBN: 1590597818).
Protecting Your Rails Ecommerce Application (Page 1 of 5 )
Creating the Form Templates
We need form templates for both the request and password resetting actions. Letís start by creatingapp/views/account/forgot_password.rhtmland adding the following code to it:
<p>Give your email address and we'll send you instructions on how to create a new one.</p> <%= form_tag %> <label for="email">Email</label><br /> <%= text_field_tag "email" %><br /> <%= submit_tag "Submit" %> <%= end_form_tag %>
The form is extremely simple, consisting of one text field for the e-mail address and a Submit button, as shown in Figure 8-4.
Figure 8-4. Forgot password? form
Notice that since weíre posting the form back to the current action, we donít even need to specify an address forform_tag.
The reset form inapp/views/account/reset_password.rhtmlis almost as simple as the request form:
Here, we just show two password fields: one for the actual password and one for a confirmation. Since theUserclass has avalidates_confirmation_ofvalidation specified for thepasswordattribute, the password confirmation is automatically checked against the password. After that, it is stripped from the newUserobject before saving. If the two passwords donít match,@usercanít be saved, and the form is shown with an error notification by using theerror_messages_forcall, as shown in Figure 8-5.
Figure 8-5. Error message when passwords do not match
We now have a working authentication system in our application. It could be easily extended to support open user registration, role-based authentication, reversible encrypted passwords, and ďremember meĒ functionality. For instructions on how to implement these functions, refer to the pluginís homepage athttp://technoweenie.stikipad.com/plugins/ show/Acts+as+Authenticated.
Note In the implementation described in this chapter, the current password of a user is not reversible. When a user forgets her password, she must create a new one. The system will not mail her the old one.