Sessions
The Session
A session store that uses an Maze:Router::Session::Store to store the sessions. This store is most useful if you don't store critical data in your sessions and you don't need them to live for extended periods of time.
This cookie-based session store is the Maze default. It is dramatically faster than the alternatives.
The cookie store used for storage is automatically configured to be the best possible option given your application's configuration.
Sessions typically contain at most a user_id and flash message; both fit within the 4K cookie size limit. A CookieOverflow exception is raised if you attempt to store more than 4K of data.
To configure the session:
# Cookie Store
Maze::Server.instance.session = {
:key => "name.session",
:store => :cookie,
:expires => 120, # 0, will make the session last as long as the browser is open, upon closing, session will be terminated
:secret => "secret"
}
# Redis Store
Maze::Server.instance.session = {
:key => "name.session",
:store => :redis,
:expires => 120,
:secret => "secret",
:redis_url => "redis://localhost:6379",
}Configure the Pipeline
Accessing the session
To store something in the session, just assign it to the key like a hash:
To remove something from the session, assign that key to be nil or usesession.delete(key)
The Flash
The flash is a special part of the session which is cleared with each request. This means that values stored there will only be available on the next request, which is useful for passing error messages etc.
It is accessed in much the same way as the session, as a hash.
Let's use the act of logging out as an example. The controller can send a message which will be displayed to the user on the next request:
Rendering the flash message
If you want a flash value to be carried over to another request, use the keep method:
Flash.now
By default, adding values to the flash will make them available to the next request, but sometimes you may want to access those values in the same request. For example, if the create action fails to save a resource and you render the new template directly, that's not going to result in a new request, but you may still want to display a message using the flash. To do this, you can use flash.now in the same way you use the normal flash.
Make sure the Flash, Session and CSRF pipelines are enabled in your routes.cr file and in the order that the scaffolding renders them.
CSRF
To use CSRF, enable the pipe in your routes.cr
Then, insert the csrf_tag helper in your forms.
How to use CSRF with Ajax
Simply call the csrf_tag helper inside your controller and return it as part of a JSON object:
In your Javascript, after getting the JSON object back, refresh your CSRF tag with the one from the server.
Last updated