In this post I’ll describe how I use the authentication gem Tachiban in my Hanami 1.3 applications.
I use a separate Hanami application to handle authentication and authorization. I’ll focus on the authorization (Rokku) in a separate post.
Authentication application elements
There are currently five main application elements that drive authentication: users, user sessions, dashboard, password reset/update and setting Tachiban defaults. I use one separate module for setting the Tachiban defaults, while I override certain Tachiban methods where appropriate.
The user attributes are defined as follows to make use of Tachiban as per prerequisites defined here.
The most relevant action for Tachiban is Create. The translate_err_mess method in the sample code below is a custom method for translating error messages. I need this to adjust translations for Slovenian, for example.
The most important thing is to setup a hashed password to be saved in the database.
2. User sessions
There are no entities required for user sessions, but only controllers and actions.
The three actions for the user sessions controller are:
In the Newaction I first set the current user to nil and also override the methods that check for the logged in user and handle session. This is needed in order to prevent an infinite loop of checking and redirecting.
The Create action finds the user trying to log in and if they are authenticated they are logged in. Otherwise the logoutmethod is called. The check_for_logged_in_userand handle_session are overridden again.
Lastly, the Destroyaction logs the user out. This acion also requires bypassing the Tachiban’s checking methods.
The dashboard controller is basically a home page for the app and thus not needed for the Tachibam implementation. I include it here to better ilustrate the entire app.
4. Password reset/update
There are no entities required for user sessions, but only controllers and actions. For both I use the EDIT/UPDATE actions. The templates are not included here.
There are two set of actions for this functionality: one for requesting the password reset (or to handle a forgotten password) and the other for updating the password.
4.2.1 Password reset UPDATE action
4.2.2 Password update EDIT action
4.2.3 Password update UPDATE action
Also don’t forget to setup the delivery configuration in the environment.rb.
In order for the code below to work these routes have to be defined:
5. Setting Tachiban defaults
In Authentication module I do the following.
Specify Tachiban’s methods that I want to call in the before block for every action.
Set default urls for my application.
Don’t forget to include this module in the application.rb.