## Please edit system and help pages ONLY in the moinmaster wiki! For more
## information, please see MoinMaster:MoinPagesEditorGroup.
##master-page:Unknown-Page
##master-date:Unknown-Date
#acl MoinPagesEditorGroup:read,write,delete,revert All:read
#format wiki
#language en
= How sessions work in MoinMoin =

Sessions in MoinMoin are implemented using the authentication framework, see HelpOnAuthentication for more details. By default, the function `MoinMoin.auth.moin_session` is contained in the `config.auth` list and is responsible for managing sessions. You can use it together with any other authentication method if you need sessions. 

As a programmer, in order to use session variables, you can use `request.session` like a dict, values stored there are automatically saved and restored if a session is available.

Code using the session framework currently includes:
 * the superuser "change user" functionality, see HelpOnSuperUser
 * the visited pages trail

== Anonymous sessions ==

Anonymous sessions are supported by including the `MoinMoin.auth.moin_anon_session` function into `config.auth` after the `MoinMoin.auth.moin_session` entry.

You also need to set `config.anonymous_cookie_lifetime`. Cookies for anonymous sessions expire after `config.anonymous_cookie_lifetime` hours (can be fractional), however, the expiry is not verified. Saved state is removed earliest an hour after the session cookie has expired.

{{{
    from MoinMoin.auth import moin_login, moin_session, moin_anon_session
    auth = [moin_login, moin_session, moin_anon_session]
    anonymous_cookie_lifetime = 1 # hour(s)
}}}

/!\ `moin_anon_session` just sets a anonymous session cookie, it does not establish a session itself (i.e. set `request.session`). You need to use `moin_session` to do that and `moin_anon_session` must be after `moin_session` in the `auth` list.

== Replacing moin_session ==
It is possible to replace `moin_session` in the `auth` configuration list. The new session handler should assign `request.session` based on a cookie or other information. The `request.session` object must be a dict-like object and it should implement session data expiry, cf. `MoinMoin.auth.SessionData`.

== Session example code ==

Here's an example macro using the session code:
{{{
#!python
# -*- coding: iso-8859-1 -*-

"""
    Tests session state.
"""

Dependencies = ['time']

def execute(macro, args):
    if 'test' in macro.request.session:
        return macro.formatter.text(macro.request.session['test'])
    import random
    value = random.randint(1, 100000)
    macro.request.session['test'] = value
    return macro.formatter.text("set to value %d" % value)
}}}
