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 )
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 => email@example.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
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
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.