In my previous post I’ve described how to use Tachiban for authentication in a Hanami 1.3 app. This post will be about using my authorization gem Rokku with Hanami applications.
Authorization application elements
There are currently four main application elements that drive authorization: users, roles, policies and a custom authorization module.
There are only two prerequisites for the user. The user entity must have an attribute of roles, which is later on specified in the corresponding policy. Below is an example of a user entity that fulfills prerequisites for both Rokku as well as Tachiban. Notice that roles are of type Array. They could also be a String in case users may only have one role.
I’ll be using named roles like new_user, admin etc. The user assigned role will be compared to the role for a specific policy.
Here is a shortened example of the new and edit templates for the user. Strings such as labels are represented by symbols to leverage the internationalization.
1.2.1 NEW template
Since the example uses the same controller for admin users and all other users, to edit the template we first need to check if the logged in user has the admin authorization to display the editing roles section for users. Then we make the required checkboxes for assigning roles.
1.2.1 EDIT template
Here we also check for the logged in user authorization. Then we make the required checkboxes for assigning roles with checked options for existing role assignments.
Each application has its own set of policies. To create a policy for the app Web and controller Notification we run the following command in the project root folder.
Rokku creates the policy file for us. As per instruction we need to uncomment the required roles and add the roles them. In the example below the role some_user is authorized for all actions.
3. Prepare the authorization check before call
To autmatically check for authorization for each request we can prepare a separate module for that. In such module Authorization we then need to make two things.
First we need to define all the controllers and their respective singluar forms to match the policy name.
Check if the currently logged in user is authorized. We do this by calling the authorized? method of the Rokku. We get the arguments for the method by splitting the controller.
Don’t forget to include this module in the application.rb.
Last but not least, we need to override the check_authorization method in all actions where we don’t require it.