Skip to content
Zachary Grafton edited this page Jan 3, 2016 · 6 revisions

onion has session support.

There is support for memory based sessions, sqlite3 sessions, and Redis sessions. Sqlite3 sessions are not specially optimized, but should work for basic servers. Now there is also a framework so developers can create their own backends.

Use of the sessions

On any request the user can ask for a session dictionary or directly for a session value:

const char *onion_request_get_session(onion_request *request, const char *key); returns the value of the session for that key. As this can be quite limiting, and more direct access to the session dictionary may be needed code can also ask for the session dict.

After using a session it must be freed. This just means that the user does not need the copy anymore, but internally the copy is used to store session changes and so on.

Full example

onion_connection_status session_request(void *, onion_request *req, onion_response *res){
  onion_dict *session=onion_request_get_session(req);
  if (onion_request_get_query(req)){
    onion_dict_add(session, "GET", onion_dict_get(onion_request_get_query(req), "data"), OD_DUP_ALL|OD_REPLACE ); // Set new value (might replace old)
  }
  const char *previous=onion_dict_get(session, "GET");
  if (previous)
    onion_request_write0(res, previous);
  onion_dict_free(session); // After use, just free it.
  return OCS_PROCESSED;
}

This handler stores in the session data the ?data= query value, and returns it. If none, returns the previously stored value, or nothing.

sqlite3 based sessions

To enable sqlite based sessions, you must be set the session backend of the onion object:

onion* o=onion_new(0);
onion_set_session_backend(o,  onion_sessions_sqlite3_new( my_sqlite3_database_filename ) );

Memory based sessions

Memory backed sessions use a normal dictionary object as the backend, but in a multithreaded server, the dictionary can be accessed by multiple threads simultaneously. In this case, you must use onion_lock_read, onion_lock_write, and onion_unlock where appropriate.

Redis based sessions

To enabled Redis backed sessions, you must set the session backend of the onion object:

onion* o = onion_new(0);
onion_set_session_backend(o, onion_sessions_redis_new(my_server_ip, my_server_port));

Cookies

Sessions are matched using cookies, carrying a random string, and currently there is no cookie authenticity test. This means that there is no data leak from the user data to the browser, but if an attacker can get access to such cookie, for the live of the session it can impersonate the user. There is no way for libonion to know that this cookie did not originate on the users browser.

If you know a way to implement a reliable cookie authenticity test, please contact me at dmoreno@coralbits.com.

Clone this wiki locally