-
Notifications
You must be signed in to change notification settings - Fork 2
The Session
The Crails::Params
object also provides a session object, allowing you to store variables that will then be saved using a method defined in config/session_store.cpp
.
By default, Crails uses the CookieStore
, which simply stores your values as cookie variables. Some modules may provide additional storing methods, for instance using a database as a backend for the store.
The session object uses a DataTree
, and as such, has a similar interface to the params
object. You can interact with your session object that way:
void Router::initialize()
{
match("GET", "/hello/:value", [](Params& params, function<void(DataTree)> callback)
{
DataTree response;
Data session = params.get_session();
response["headers"]["Content-Type"] = "text/plain";
if (session["old_value"].exists()) // Checking if the session variable already exists
response["body"] = "Last time, we greeted " + session["old_value"].as<std::string>(); // Casting the session variable as a string
else
response["body"] = "This is the first time we greet someone";
session["old_value"] = params["value"].as<std::string>(); // Storing the current 'value' params in the session variable for the next request
callback(response);
});
}
If you are using a Crails' controllers, you also have access to the session object through the protected Crails::Controller::session
attribute.
Cookie encryption is disabled by default. You may enable it by editing the config/salt.cpp
file, and setting the value of const bool CookieData::use_encryption
to true
.
Using encryption for your cookies may significantly impact your response time, and should only be used when your cookies may contain private data, or anything that may be used to steal a session.
The laziest way to implement a user session would look like this:
session["user_id"] = 42;
If you do this, cookie encryption must be enabled. Otherwise, anyone could steal any user's session without any effort. Still, while this is the easiest acceptable solution, this is not the method we recommend to implement user sessions.
If you are only going to use cookies to maintain a user logged, please consider disabling the cookie encryption, and following the OWASP session management guidelines instead, only storing a 128bit long session ID in a cookie variable.
Session stores can be useful, but they are sometimes not needed. And we happen to notice that, for really quick queries, parsing and generating cookies can be one of the most time-consuming tasks while responding to a query (especially when using encrypted cookies). If you don't need it, this feature can easily be disabled by editing your config/session_store.cpp
file and make it look like this:
#include <crails/session_store/no_session_store.hpp>
#include <crails/session_store.hpp>
using namespace Crails;
USE_SESSION_STORE(NoSessionStore)