Agile Web Development with Rails, Edition 4

Agile Web Development with Rails, Edition 4

14.4 Iteration I4: Adding a Sidebar 14.2 Iteration I2: Authenticating Users

14.3 Iteration I3: Limiting Access

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 cart operations

edit app/controllers/carts_controller.rb
class CartsController < ApplicationController
    skip_before_filter :authorize, only: [:create, :update, :destroy]
 

whitelist line_item operations

edit app/controllers/line_items_controller.rb
class LineItemsController < ApplicationController
    skip_before_filter :authorize, only: :create
 

whitelist order operations

edit app/controllers/orders_controller.rb
class OrdersController < ApplicationController
    skip_before_filter :authorize, only: [:new, :create]
 

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
Run options: --seed 42025
 
# Running tests:
 
.......
 
Finished tests in 0.511487s, 13.6856 tests/s, 54.7423 assertions/s.
 
7 tests, 28 assertions, 0 failures, 0 errors, 0 skips
Run options: --seed 12490
 
# Running tests:
 
...............................................
 
Finished tests in 2.333847s, 20.1384 tests/s, 41.5623 assertions/s.
 
47 tests, 97 assertions, 0 failures, 0 errors, 0 skips
DEPRECATION WARNING: ActionController::Integration is deprecated and will be removed, use ActionDispatch::Integration instead. (called from <top (required)> at /home/rubys/git/awdwr/edition4/work-200-40/depot/test/integration/dsl_user_stories_test.rb:3)
DEPRECATION WARNING: ActionController::IntegrationTest is deprecated and will be removed, use ActionDispatch::IntegrationTest instead. (called from <top (required)> at /home/rubys/git/awdwr/edition4/work-200-40/depot/test/integration/dsl_user_stories_test.rb:3)
Run options: --seed 6691
 
# Running tests:
 
...
 
Finished tests in 1.427372s, 2.1018 tests/s, 32.9276 assertions/s.
 
3 tests, 47 assertions, 0 failures, 0 errors, 0 skips

14.4 Iteration I4: Adding a Sidebar 14.2 Iteration I2: Authenticating Users