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.
1. Users
1.1 Entities
The user attributes are defined as follows to make use of Tachiban as per prerequisites defined here.
1.2 Controllers
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.
1.3 Routes
2. User sessions
2.1 Entities
There are no entities required for user sessions, but only controllers and actions.
2.2 Controllers
The three actions for the user sessions controller are:
New
Create and
Destroy.
2.2.1 New
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.
2.2.2 Create
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.
2.2.3 Destroy
Lastly, the Destroyaction logs the user out. This acion also requires bypassing the Tachiban’s checking methods.
2.3 Routes
3. Dashboard
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.
Routes
4. Password reset/update
4.1 Entities
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.
4.2 Controllers
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
4.3 Mailers
Also don’t forget to setup the delivery configuration in the environment.rb.
4.4 Routes
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.