1# -*- coding: iso-8859-1 -*-
2"""
3MoinMoin - cleansessions script
4
5@copyright: 2009 MoinMoin:ReimarBauer,
6            2010 MoinMoin:ThomasWaldmann
7@license: GNU GPL, see COPYING for details.
8"""
9
10import os, time
11
12from MoinMoin import user
13from MoinMoin.script import MoinScript
14
15class PluginScript(MoinScript):
16    """\
17Purpose:
18========
19This script allows you to clean up session files (usually used to maintain
20a "logged-in session" for http(s) or xmlrpc).
21
22Detailed Instructions:
23======================
24General syntax: moin [options] maint cleansessions [cleansessions-options]
25
26[options] usually should be:
27    --config-dir=/path/to/my/cfg/ --wiki-url=http://wiki.example.org/
28
29[cleansessions-options] see below:
30    --name     remove sessions only for user NAME (default: all users)
31    --all      remove all sessions (default: remove outdated sessions)
32"""
33
34    def __init__(self, argv, def_values):
35        MoinScript.__init__(self, argv, def_values)
36
37        self.parser.add_option(
38            "--name", metavar="NAME", dest="username",
39            help="remove sessions only for user NAME (default: all users)"
40        )
41        self.parser.add_option(
42            "--all", action="store_true", dest="all_sessions",
43            help="remove all sessions (default: remove outdated sessions)"
44        )
45
46    def mainloop(self):
47        self.init_request()
48        request = self.request
49        checks = []
50
51        if not self.options.all_sessions:
52            now = time.time()
53            def session_expired(session):
54                try:
55                    return session['expires'] < now
56                except KeyError:
57                    # this is likely a pre-1.9.1 session file without expiry
58                    return True # consider it expired
59            checks.append(session_expired)
60
61        if self.options.username:
62            u = user.User(request, None, self.options.username)
63            if not u.exists():
64                print 'User "%s" does not exist!' % self.options.username
65                return
66            else:
67                def user_matches(session):
68                    try:
69                        return session['user.id'] == u.id
70                    except KeyError:
71                        return False
72                checks.append(user_matches)
73
74        session_service = request.cfg.session_service
75        for sid in session_service.get_all_session_ids(request):
76            session = session_service.get_session(request, sid)
77
78            # if ALL conditions are met, the session will be destroyed
79            killit = True
80            for check in checks:
81                killit = killit and check(session)
82
83            if killit:
84                session_service.destroy_session(request, session)
85
86