Securing the Login for a Rails Ecommerce Application
In the first part of this four-part series we started to learn about security for an ecommerce application in Ruby-on-Rails. In this second part we're going to test some of what we did in the first part, and implement some important login features. This article is excerpted from chapter eight of the book Practical Rails Projects, written by Eldon Alameda (Apress; ISBN: 1590597818).
Securing the Login for a Rails Ecommerce Application (Page 1 of 4 )
Testing Redirection
The last part of the story was that after successful login, George is redirected to the page he tried to access in the first place.acts_as_authenticatedshould do this for us automatically. Let’s extend our integration test (authentication_test.rb) as follows to make sure.
class AuthenticationTest < ActionController::IntegrationTest def setup User.create(:login => "george", :email => george@emporium.com, :password => "cheetah", :password_confirmation => "cheetah") end
def test_successful_login george = enter_site(:george) george.tries_to_go_to_admin george.logs_in_successfully("george", "cheetah") end
private
module BrowsingTestDSL include ERB::Util attr_writer :name
def tries_to_go_to_admin get "/admin/book/new" assert_response :redirect assert_redirected_to "/account/login" end
def logs_in_successfully(login, password) post_login(login, password) assert_response :redirect assert_redirected_to "/admin/book/new" end
private
def post_login(login, password) post "/account/login", :login => login, :password => password end end
def enter_site(name) open_session do |session| session.extend(BrowsingTestDSL) session.name = name yield session if block_given? end end end
In the beginning of the test, we use thesetupmethod, which is automatically run before every test method, to create George as a user in the system. Then we create another DSL method for logging in to the system successfully. We extracted the actual posting of the login credentials to a private method, because we will need the same code later when we test a failed login. All our new method tests is that after successful login, George is redirected to/admin/book/new, the page he tried to access before he was thrown to the login page.
Running the test again shows that the authentication system indeed remembers where George was heading:
$ ruby test/integration/authentication_test.rb
-------------------------------------------- Loaded suite test/integration/authentication_test Started . Finished in 0.192056 seconds.
Trying to access the admin pages in a browser confirms what the test already says. As you can see in Figure 8-1, if you haven’t logged in successfully, you’re redirected to the login page.
Figure 8-1. Accessing the admin pages redirects to the login page