In the last screencast I created an authentication system for a vanilla Ruby on Rails 4.2 application. In this screencast we will add basic authorization to it.
We are going to create a blog application. Any logged in user will be able to create new posts. Posts can be edited and destroyed by the user himself but not by anybody else.
Please visit the Authentication Screencast and create a new
blog application the same way. You should be able to create a new account and log into that account. A
current_user method and a
current_user helper should be available.
We start with a
Because we render the flash messages in
application.html.erb we can delete them in the following files:
Post model needs a couple of validations and a
User model needs a
has_many association to the
Because we’ll take care of the
user_id attribute in the controller we can delete the following code in the Post form:
And because we will not send the
user_id through the form we can remove that from the
post_params method in the
Post controller too:
Lastly we have to change the
create method in the same controller to build a new post with the
For easier navigation I’ll add two links to our navigation.
Now a user can create, edit and destroy a post. But unfortunately any user can edit any post now and even somebody who is not logged in at all could edit and destroy a post.
We need authorization to fix that.
We create a private
authorize method in the
Post controller and trigger it with a
before_action. Because we don’t need it for the
show views we can
Obvioulsy it doesn’t make any sense to show a link to a person who is not logged in. A couple of
if clauses and the
current_user helper will fix that:
After that we’ll do the same in the
Now you are good to go. Have fun with your new authorization system!
Please have a look at ruby-toolbox.com for a detailed list of available authorization gems. Do not use
cancan because that is not longer maintained!
cancancan seems to be a good alternative (but I’ve never tried it). Many people like