27.02.2013 Views

Rails%203%20In%20Action

Rails%203%20In%20Action

Rails%203%20In%20Action

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

8.4 Blocking access to tickets<br />

Blocking access to tickets<br />

When implementing permissions, you have to be careful to ensure that all users who<br />

should have access to something do, and all users who shouldn’t have access to something<br />

don’t. All of the TicketsController’s actions are still available to all users<br />

because it has no permission checking. If you leave it in that state, users who are<br />

unable to see the project can still make requests to the actions inside Tickets-<br />

Controller. They shouldn’t be able to do anything to the tickets in a project if they<br />

don’t have permission to view tickets for it. Let’s implement permission checking to<br />

remedy this problem.<br />

8.4.1 Locking out the bad guys<br />

To prevent users from seeing tickets in a project they’re unauthorized to see, you must<br />

lock down the show action of TicketsController.<br />

To test that when you put this restriction in place, it’s correct, write a spec in the<br />

spec/controllers/tickets_controller_spec.rb file, just as you did for the Projects-<br />

Controller. This file should now look like the following listing.<br />

Listing 8.5 spec/controllers/tickets_controller_spec.rb<br />

require 'spec_helper'<br />

describe TicketsController do<br />

let(:user) { create_user! }<br />

let(:project) { Factory(:project) }<br />

let(:ticket) { Factory(:ticket, :project => project,<br />

:user => user) }<br />

context "standard users" do<br />

it "cannot access a ticket for a project" do<br />

sign_in(:user, user)<br />

get :show, :id => ticket.id, :project_id => project.id<br />

response.should redirect_to(root_path)<br />

flash[:alert].should eql("The project you were looking for could not be<br />

found.")<br />

end<br />

end<br />

end<br />

This test sets up a project, a ticket, and a user who has no explicit permission to view<br />

the project and therefore shouldn’t be able to view the ticket. You test this spec by<br />

signing in as the unauthorized user and trying to go to the show action for this ticket,<br />

which requires you to pass through a project_id to help it find what project the<br />

ticket is in. The test should pass if the user is redirected to the root_path and if, upon<br />

the user seeing the flash[:alert], the application denies all knowledge of this project<br />

ever having existed.<br />

When you run this test using bin/rspec spec/controllers/tickets_controller<br />

_spec.rb, you see the ticket factory is undefined:<br />

No such factory: ticket (ArgumentError)<br />

183

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!