[web] move abstract session manager to web/sessions

Related to #1381328.

authorAurelien Campeas <aurelien.campeas@logilab.fr>
changeset8bc76a63b4ca
branchdefault
phasedraft
hiddenyes
parent revision#4a3c5628c66d [repository] rename session -> cnx
child revision#f3d653d3e6b2 [web] move AbstractAuthManager near its immediate concrete subclass
files modified by this revision
web/application.py
web/views/sessions.py
# HG changeset patch
# User Aurelien Campeas <aurelien.campeas@logilab.fr>
# Date 1392305561 -3600
# Thu Feb 13 16:32:41 2014 +0100
# Node ID 8bc76a63b4caeb73cea88c82baae93d5146e8625
# Parent 4a3c5628c66dde124f8576d69ac6c30c28033570
[web] move abstract session manager to web/sessions

Related to #1381328.

diff --git a/web/application.py b/web/application.py
@@ -58,70 +58,10 @@
1          with anon_cnx:
2              yield req
3      finally:
4          req.set_cnx(orig_cnx)
5 
6 -class AbstractSessionManager(component.Component):
7 -    """manage session data associated to a session identifier"""
8 -    __regid__ = 'sessionmanager'
9 -
10 -    def __init__(self, repo):
11 -        vreg = repo.vreg
12 -        self.session_time = vreg.config['http-session-time'] or None
13 -        self.authmanager = vreg['components'].select('authmanager', repo=repo)
14 -        interval = (self.session_time or 0) / 2.
15 -        if vreg.config.anonymous_user()[0] is not None:
16 -            self.cleanup_anon_session_time = vreg.config['cleanup-anonymous-session-time'] or 5 * 60
17 -            assert self.cleanup_anon_session_time > 0
18 -            if self.session_time is not None:
19 -                self.cleanup_anon_session_time = min(self.session_time,
20 -                                                     self.cleanup_anon_session_time)
21 -            interval = self.cleanup_anon_session_time / 2.
22 -        # we don't want to check session more than once every 5 minutes
23 -        self.clean_sessions_interval = max(5 * 60, interval)
24 -
25 -    def clean_sessions(self):
26 -        """cleanup sessions which has not been unused since a given amount of
27 -        time. Return the number of sessions which have been closed.
28 -        """
29 -        self.debug('cleaning http sessions')
30 -        session_time = self.session_time
31 -        closed, total = 0, 0
32 -        for session in self.current_sessions():
33 -            total += 1
34 -            last_usage_time = session.mtime
35 -            no_use_time = (time() - last_usage_time)
36 -            if session.anonymous_session:
37 -                if no_use_time >= self.cleanup_anon_session_time:
38 -                    self.close_session(session)
39 -                    closed += 1
40 -            elif session_time is not None and no_use_time >= session_time:
41 -                self.close_session(session)
42 -                closed += 1
43 -        return closed, total - closed
44 -
45 -    def current_sessions(self):
46 -        """return currently open sessions"""
47 -        raise NotImplementedError()
48 -
49 -    def get_session(self, req, sessionid):
50 -        """return existing session for the given session identifier"""
51 -        raise NotImplementedError()
52 -
53 -    def open_session(self, req):
54 -        """open and return a new session for the given request.
55 -
56 -        raise :exc:`cubicweb.AuthenticationError` if authentication failed
57 -        (no authentication info found or wrong user/password)
58 -        """
59 -        raise NotImplementedError()
60 -
61 -    def close_session(self, session):
62 -        """close session on logout or on invalid session detected (expired out,
63 -        corrupted...)
64 -        """
65 -        raise NotImplementedError()
66 
67 
68  class AbstractAuthenticationManager(component.Component):
69      """authenticate user associated to a request and check session validity"""
70      __regid__ = 'authmanager'
diff --git a/web/views/sessions.py b/web/views/sessions.py
@@ -13,22 +13,87 @@
71  # FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more
72  # details.
73  #
74  # You should have received a copy of the GNU Lesser General Public License along
75  # with CubicWeb.  If not, see <http://www.gnu.org/licenses/>.
76 -"""web session component: by dfault the session is actually the db connection
77 -object :/
78 -"""
79 -
80 +"""web session: by default the session is actually the db connection """
81  __docformat__ = "restructuredtext en"
82 
83  from time import time
84 
85 -from cubicweb import (RepositoryError, Unauthorized, AuthenticationError,
86 -                      BadConnectionId)
87 -from cubicweb.web import InvalidSession, Redirect
88 -from cubicweb.web.application import AbstractSessionManager
89 +from cubicweb import RepositoryError, Unauthorized, BadConnectionId
90 +from cubicweb.web import InvalidSession, component
91 +
92 +
93 +class AbstractSessionManager(component.Component):
94 +    """manage session data associated to a session identifier"""
95 +    __abstract__ = True
96 +    __regid__ = 'sessionmanager'
97 +
98 +    def __init__(self, repo):
99 +        vreg = repo.vreg
100 +        self.session_time = vreg.config['http-session-time'] or None
101 +        self.authmanager = vreg['components'].select('authmanager', repo=repo)
102 +        interval = (self.session_time or 0) / 2.
103 +        if vreg.config.anonymous_user()[0] is not None:
104 +            self.cleanup_anon_session_time = vreg.config['cleanup-anonymous-session-time'] or 5 * 60
105 +            assert self.cleanup_anon_session_time > 0
106 +            if self.session_time is not None:
107 +                self.cleanup_anon_session_time = min(self.session_time,
108 +                                                     self.cleanup_anon_session_time)
109 +            interval = self.cleanup_anon_session_time / 2.
110 +        # we don't want to check session more than once every 5 minutes
111 +        self.clean_sessions_interval = max(5 * 60, interval)
112 +
113 +    def clean_sessions(self):
114 +        """cleanup sessions which has not been unused since a given amount of
115 +        time. Return the number of sessions which have been closed.
116 +        """
117 +        self.debug('cleaning http sessions')
118 +        session_time = self.session_time
119 +        closed, total = 0, 0
120 +        for session in self.current_sessions():
121 +            total += 1
122 +            try:
123 +                last_usage_time = session.cnx.check()
124 +            except AttributeError:
125 +                last_usage_time = session.mtime
126 +            except BadConnectionId:
127 +                self.close_session(session)
128 +                closed += 1
129 +            else:
130 +                no_use_time = (time() - last_usage_time)
131 +                if session.anonymous_session:
132 +                    if no_use_time >= self.cleanup_anon_session_time:
133 +                        self.close_session(session)
134 +                        closed += 1
135 +                elif session_time is not None and no_use_time >= session_time:
136 +                    self.close_session(session)
137 +                    closed += 1
138 +        return closed, total - closed
139 +
140 +    def current_sessions(self):
141 +        """return currently open sessions"""
142 +        raise NotImplementedError()
143 +
144 +    def get_session(self, req, sessionid):
145 +        """return existing session for the given session identifier"""
146 +        raise NotImplementedError()
147 +
148 +    def open_session(self, req):
149 +        """open and return a new session for the given request.
150 +
151 +        raise :exc:`cubicweb.AuthenticationError` if authentication failed
152 +        (no authentication info found or wrong user/password)
153 +        """
154 +        raise NotImplementedError()
155 +
156 +    def close_session(self, session):
157 +        """close session on logout or on invalid session detected (expired out,
158 +        corrupted...)
159 +        """
160 +        raise NotImplementedError()
161 
162 
163  class InMemoryRepositorySessionManager(AbstractSessionManager):
164      """manage session data associated to a session identifier"""
165