14.4 Iteration I4: Adding a Sidebar 14.2 Iteration I2: Authenticating Users
require authorization before every access
edit app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
before_filter :authorize
# ...
protected
def authorize
unless User.find_by_id(session[:user_id])
redirect_to login_url, :notice => "Please log in"
end
end
end
whitelist the sessions and store controllers
edit app/controllers/sessions_controller.rb
class SessionsController < ApplicationController
skip_before_filter :authorize
edit app/controllers/store_controller.rb
class StoreController < ApplicationController
skip_before_filter :authorize
whitelist order operations
edit app/controllers/orders_controller.rb
class OrdersController < ApplicationController
skip_before_filter :authorize, :only => [:new, :create]
whitelist line_item operations
edit app/controllers/line_items_controller.rb
class LineItemsController < ApplicationController
skip_before_filter :authorize, :only => :create
whitelist cart operations
edit app/controllers/carts_controller.rb
class CartsController < ApplicationController
skip_before_filter :authorize, :only => [:create, :update, :destroy]
def invalid_cart
logger.error "Attempt to access invalid cart #{params[:id]}"
redirect_to store_url, :notice => 'Invalid cart'
end
end
Cause all tests to do an implicit login
edit test/test_helper.rb
class ActiveSupport::TestCase
# ...
# Add more helper methods to be used by all tests here...
def login_as(user)
session[:user_id] = users(user).id
end
def logout
session.delete :user_id
end
def setup
login_as :one if defined? session
end
end
Show that the now pass
rake test
Loaded suite /home/rubys/.rvm/gems/ruby-1.8.7-p374/gems/rake-10.1.1/lib/rake/rake_test_loader
Started
[deprecated] I18n.enforce_available_locales will default to true in the future. If you really want to skip validation of your locale you can set I18n.enforce_available_locales = false to avoid this message.
..........
Finished in 0.2166 seconds.
10 tests, 31 assertions, 0 failures, 0 errors
Loaded suite /home/rubys/.rvm/gems/ruby-1.8.7-p374/gems/rake-10.1.1/lib/rake/rake_test_loader
Started
[deprecated] I18n.enforce_available_locales will default to true in the future. If you really want to skip validation of your locale you can set I18n.enforce_available_locales = false to avoid this message.
...............................................
Finished in 0.953942 seconds.
47 tests, 79 assertions, 0 failures, 0 errors
Loaded suite /home/rubys/.rvm/gems/ruby-1.8.7-p374/gems/rake-10.1.1/lib/rake/rake_test_loader
Started
[deprecated] I18n.enforce_available_locales will default to true in the future. If you really want to skip validation of your locale you can set I18n.enforce_available_locales = false to avoid this message.
...
Finished in 0.654022 seconds.
3 tests, 75 assertions, 0 failures, 0 errors
14.4 Iteration I4: Adding a Sidebar 14.2 Iteration I2: Authenticating Users