Rails Application with Authentication and Authorization

Vamsi Krishna

1 min read

This is a small blog about applying authorization to an application and how to write unit,functional and integration tests for the application in the end, so the first blog I will cover how to do simple authorization in rails and in the second part of the application I will write the complete test cases for this application.
The scenario: Application – Managing Contents
(list of actions available are index,show,new,create,edit,update and destroy)
The application has three roles Admin,Publisher and member
Admin – has access to all the actions.
Publisher – has access to everything except destroy action.
member – can only access index page and show page.
There are so many plugins available outside for implementing this Authorization. I decided to do it on my own since this is a simple authorization application, but if you want to go for complex scenarios I suggest you check this link
Ok enough talk, let’s digg inside the code.
This application is completely about Authorization, I provided a simple authentication but, for providing proper authentication the plugins I suggest are auth_logic or restful_authentication(plugins) or you can write your own authentication code. Anyway let’s go with the code.
In this application I created login_controller for authentication, it’s a simple form with one textfield which will expect you to enter the user type(member,publisher or admin).
To access any action first of all the user must be a registered user that is member, Admin can access every action of the application and Publisher can do everything except deleting the content.
Let me show the code for authentication
So I created a scaffold for content application.
So once you successfully logged in the the role will be saved in a session.
So the code is self explanatory, you can move this to application controller if you want to applay this authorization than to more than one controller.
admin?.publisher? are can be used a helpers in the views to hide the links for users that are not supposed to show
for example:
[source language=”Ruby”]
<% if publisher? || admin? %>

<%= link_to 'Edit', edit_content_path(content) %>

<% end %>
<% if admin?<%= link_to 'Destroy', content, :confirm => ‘Are you sure?’, :method => :delete %>

<% end %>
So this is the simple authorization I provide for the system, if your system is complex there are plugins available for authorization you can check this blog post for that

Related posts:

Leave a Reply

Your email address will not be published. Required fields are marked *