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.

194 CHAPTER 8 More authorization<br />

You don’t have to put the last two lines in their own method because you won’t use<br />

them more than once. When you run this spec, it fails on the final line rather than on<br />

the third line:<br />

1) TicketsController standard users with permission to view the project<br />

cannot delete a ticket without permission<br />

Failure/Error: flash[:alert].should eql<br />

➥("You cannot delete tickets from this project.")<br />

This error occurs because the destroy action is actually being processed, and it redirects<br />

the user to the project once it’s complete. The spec doesn’t know the difference<br />

between a redirect from within the action or within the before_filter, nor should it.<br />

To make this spec pass, define a new method called authorize_delete! at the bottom<br />

of the TicketsController:<br />

def authorize_delete!<br />

if !current_user.admin? && cannot?(:"delete tickets", @project)<br />

flash[:alert] = "You cannot delete tickets from this project."<br />

redirect_to @project<br />

end<br />

end<br />

Then you can call this method in a before_filter too:<br />

before_filter :authorize_delete!, :only => :destroy<br />

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

_spec.rb, it’s all passing:<br />

6 examples, 0 failures<br />

Now that you’re stopping users without permission, how goes your feature? Run bin/<br />

cucumber features/deleting_tickets.feature to find out:<br />

1 scenario (1 passed)<br />

12 steps (12 passed)<br />

Great! With this last permission in place, all the actions in the TicketsController are<br />

restricted to their appropriate users. Let’s make a commit:<br />

git add .<br />

git commit -m "Restrict destroy action to only people with permission"<br />

git push<br />

Because the controller’s actions are restricted, the links associated with these actions<br />

should be hidden from users who are unable to perform these actions.<br />

8.7.2 Hiding links based on permission<br />

To ensure that these links are hidden from those who shouldn’t be able to see them<br />

but are still visible to admins (because admins should be able to do everything), you<br />

use features/hidden_links.feature. Start with the New Ticket link by adding the scenarios<br />

from the following listing.

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

Saved successfully!

Ooh no, something went wrong!