author | Adrien Di Mascio <Adrien.DiMascio@logilab.fr> |
Thu, 14 May 2009 16:32:20 +0200 | |
changeset 1827 | 93840d187f26 |
parent 1802 | d628defebc17 |
child 1977 | 606923dff11b |
permissions | -rw-r--r-- |
0 | 1 |
"""persistent sessions stored in big table |
2 |
||
3 |
:organization: Logilab |
|
635
305da8d6aa2d
require_group/match_user_group -> match_user_groups
sylvain.thenault@logilab.fr
parents:
0
diff
changeset
|
4 |
:copyright: 2008-2009 LOGILAB S.A. (Paris, FRANCE), all rights reserved. |
0 | 5 |
:contact: http://www.logilab.fr/ -- mailto:contact@logilab.fr |
6 |
||
7 |
XXX TODO: |
|
8 |
* cleanup persistent session |
|
9 |
* use user as ancestor? |
|
10 |
""" |
|
11 |
__docformat__ = "restructuredtext en" |
|
12 |
||
13 |
from pickle import loads, dumps |
|
14 |
from time import localtime, strftime |
|
15 |
||
16 |
from logilab.common.decorators import cached, clear_cache |
|
17 |
||
1131
544609e83317
pylint cleanup, no more need for mx datetime conversion
sylvain.thenault@logilab.fr
parents:
742
diff
changeset
|
18 |
from cubicweb import BadConnectionId |
0 | 19 |
from cubicweb.dbapi import Connection, ConnectionProperties, repo_connect |
669
5d2132832f03
start with explicit registration
sylvain.thenault@logilab.fr
parents:
635
diff
changeset
|
20 |
from cubicweb.selectors import none_rset, match_user_groups |
0 | 21 |
from cubicweb.server.session import Session |
22 |
from cubicweb.web import InvalidSession |
|
23 |
from cubicweb.web.application import AbstractSessionManager |
|
24 |
from cubicweb.web.application import AbstractAuthenticationManager |
|
25 |
||
26 |
from google.appengine.api.datastore import Key, Entity, Get, Put, Delete, Query |
|
27 |
from google.appengine.api.datastore_errors import EntityNotFoundError |
|
28 |
from google.appengine.api.datastore_types import Blob |
|
29 |
||
30 |
try: |
|
31 |
del Connection.__del__ |
|
32 |
except AttributeError: |
|
33 |
pass # already deleted |
|
34 |
||
35 |
||
36 |
class GAEAuthenticationManager(AbstractAuthenticationManager): |
|
37 |
"""authenticate user associated to a request and check session validity, |
|
38 |
using google authentication service |
|
39 |
""" |
|
40 |
||
41 |
def __init__(self, *args, **kwargs): |
|
42 |
super(GAEAuthenticationManager, self).__init__(*args, **kwargs) |
|
43 |
self._repo = self.config.repository(vreg=self.vreg) |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1131
diff
changeset
|
44 |
|
0 | 45 |
def authenticate(self, req, _login=None, _password=None): |
46 |
"""authenticate user and return an established connection for this user |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1131
diff
changeset
|
47 |
|
0 | 48 |
:raise ExplicitLogin: if authentication is required (no authentication |
49 |
info found or wrong user/password) |
|
50 |
""" |
|
51 |
if _login is not None: |
|
52 |
login, password = _login, _password |
|
53 |
else: |
|
54 |
login, password = req.get_authorization() |
|
55 |
# remove possibly cached cursor coming from closed connection |
|
56 |
clear_cache(req, 'cursor') |
|
57 |
cnxprops = ConnectionProperties(self.vreg.config.repo_method, |
|
58 |
close=False, log=False) |
|
59 |
cnx = repo_connect(self._repo, login, password, cnxprops=cnxprops) |
|
60 |
self._init_cnx(cnx, login, password) |
|
61 |
# associate the connection to the current request |
|
62 |
req.set_connection(cnx) |
|
63 |
return cnx |
|
64 |
||
65 |
def _init_cnx(self, cnx, login, password): |
|
66 |
cnx.anonymous_connection = self.config.is_anonymous_user(login) |
|
67 |
cnx.vreg = self.vreg |
|
68 |
cnx.login = login |
|
69 |
cnx.password = password |
|
70 |
||
71 |
||
72 |
class GAEPersistentSessionManager(AbstractSessionManager): |
|
73 |
"""manage session data associated to a session identifier""" |
|
74 |
||
75 |
def __init__(self, *args, **kwargs): |
|
76 |
super(GAEPersistentSessionManager, self).__init__(*args, **kwargs) |
|
77 |
self._repo = self.config.repository(vreg=self.vreg) |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1131
diff
changeset
|
78 |
|
0 | 79 |
def get_session(self, req, sessionid): |
80 |
"""return existing session for the given session identifier""" |
|
81 |
# search a record for the given session |
|
82 |
key = Key.from_path('CubicWebSession', 'key_' + sessionid, parent=None) |
|
83 |
try: |
|
84 |
record = Get(key) |
|
85 |
except EntityNotFoundError: |
|
86 |
raise InvalidSession() |
|
87 |
repo = self._repo |
|
88 |
if self.has_expired(record): |
|
89 |
repo._sessions.pop(sessionid, None) |
|
90 |
Delete(record) |
|
91 |
raise InvalidSession() |
|
92 |
# associate it with a repository session |
|
93 |
try: |
|
94 |
reposession = repo._get_session(sessionid) |
|
95 |
user = reposession.user |
|
96 |
# touch session to avoid closing our own session when sessions are |
|
97 |
# cleaned (touch is done on commit/rollback on the server side, too |
|
98 |
# late in that case) |
|
99 |
reposession._touch() |
|
100 |
except BadConnectionId: |
|
101 |
# can't found session in the repository, this probably mean the |
|
102 |
# session is not yet initialized on this server, hijack the repo |
|
103 |
# to create it |
|
104 |
# use an internal connection |
|
105 |
ssession = repo.internal_session() |
|
106 |
# try to get a user object |
|
107 |
try: |
|
108 |
user = repo.authenticate_user(ssession, record['login'], |
|
109 |
record['password']) |
|
110 |
finally: |
|
111 |
ssession.close() |
|
112 |
reposession = Session(user, self._repo, _id=sessionid) |
|
113 |
self._repo._sessions[sessionid] = reposession |
|
114 |
cnx = Connection(self._repo, sessionid) |
|
115 |
return self._get_proxy(req, record, cnx, user) |
|
116 |
||
117 |
def open_session(self, req): |
|
118 |
"""open and return a new session for the given request""" |
|
119 |
cnx = self.authmanager.authenticate(req) |
|
120 |
# avoid rebuilding a user |
|
121 |
user = self._repo._get_session(cnx.sessionid).user |
|
122 |
# build persistent record for session data |
|
123 |
record = Entity('CubicWebSession', name='key_' + cnx.sessionid) |
|
124 |
record['login'] = cnx.login |
|
125 |
record['password'] = cnx.password |
|
126 |
record['anonymous_connection'] = cnx.anonymous_connection |
|
127 |
Put(record) |
|
128 |
return self._get_proxy(req, record, cnx, user) |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1131
diff
changeset
|
129 |
|
0 | 130 |
def close_session(self, proxy): |
131 |
"""close session on logout or on invalid session detected (expired out, |
|
132 |
corrupted...) |
|
133 |
""" |
|
134 |
proxy.close() |
|
135 |
||
136 |
def current_sessions(self): |
|
137 |
for record in Query('CubicWebSession').Run(): |
|
138 |
yield ConnectionProxy(record) |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1131
diff
changeset
|
139 |
|
0 | 140 |
def _get_proxy(self, req, record, cnx, user): |
141 |
proxy = ConnectionProxy(record, cnx, user) |
|
142 |
user.req = req |
|
143 |
req.set_connection(proxy, user) |
|
144 |
return proxy |
|
145 |
||
146 |
||
147 |
class ConnectionProxy(object): |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1131
diff
changeset
|
148 |
|
0 | 149 |
def __init__(self, record, cnx=None, user=None): |
150 |
self.__record = record |
|
151 |
self.__cnx = cnx |
|
152 |
self.__user = user |
|
153 |
self.__data = None |
|
154 |
self.__is_dirty = False |
|
155 |
self.sessionid = record.key().name()[4:] # remove 'key_' prefix |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1131
diff
changeset
|
156 |
|
0 | 157 |
def __repr__(self): |
158 |
sstr = '<ConnectionProxy %s' % self.sessionid |
|
159 |
if self.anonymous_connection: |
|
160 |
sstr += ' (anonymous)' |
|
161 |
elif self.__user: |
|
162 |
sstr += ' for %s' % self.__user.login |
|
163 |
sstr += ', last used %s>' % strftime('%T', localtime(self.last_usage_time)) |
|
164 |
return sstr |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1131
diff
changeset
|
165 |
|
0 | 166 |
def __getattribute__(self, name): |
167 |
try: |
|
168 |
return super(ConnectionProxy, self).__getattribute__(name) |
|
169 |
except AttributeError: |
|
170 |
return getattr(self.__cnx, name) |
|
171 |
||
172 |
def _set_last_usage_time(self, value): |
|
173 |
self.__is_dirty = True |
|
174 |
self.__record['last_usage_time'] = value |
|
175 |
def _get_last_usage_time(self): |
|
176 |
return self.__record['last_usage_time'] |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1131
diff
changeset
|
177 |
|
0 | 178 |
last_usage_time = property(_get_last_usage_time, _set_last_usage_time) |
179 |
||
180 |
@property |
|
181 |
def anonymous_connection(self): |
|
182 |
# use get() for bw compat if sessions without anonymous information are |
|
183 |
# found. Set default to True to limit lifetime of those sessions. |
|
184 |
return self.__record.get('anonymous_connection', True) |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1131
diff
changeset
|
185 |
|
0 | 186 |
@property |
187 |
@cached |
|
188 |
def data(self): |
|
189 |
if self.__record.get('data') is not None: |
|
190 |
try: |
|
191 |
return loads(self.__record['data']) |
|
192 |
except: |
|
193 |
self.__is_dirty = True |
|
194 |
self.exception('corrupted session data for session %s', |
|
195 |
self.__cnx) |
|
196 |
return {} |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1131
diff
changeset
|
197 |
|
0 | 198 |
def get_session_data(self, key, default=None, pop=False): |
199 |
"""return value associated to `key` in session data""" |
|
200 |
if pop: |
|
201 |
try: |
|
202 |
value = self.data.pop(key) |
|
203 |
self.__is_dirty = True |
|
204 |
return value |
|
205 |
except KeyError: |
|
206 |
return default |
|
207 |
else: |
|
208 |
return self.data.get(key, default) |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1131
diff
changeset
|
209 |
|
0 | 210 |
def set_session_data(self, key, value): |
211 |
"""set value associated to `key` in session data""" |
|
212 |
self.data[key] = value |
|
213 |
self.__is_dirty = True |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1131
diff
changeset
|
214 |
|
0 | 215 |
def del_session_data(self, key): |
216 |
"""remove value associated to `key` in session data""" |
|
217 |
try: |
|
218 |
del self.data[key] |
|
219 |
self.__is_dirty = True |
|
220 |
except KeyError: |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1131
diff
changeset
|
221 |
pass |
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1131
diff
changeset
|
222 |
|
0 | 223 |
def commit(self): |
224 |
if self.__is_dirty: |
|
225 |
self.__save() |
|
226 |
self.__cnx.commit() |
|
227 |
||
228 |
def rollback(self): |
|
229 |
self.__save() |
|
230 |
self.__cnx.rollback() |
|
231 |
||
232 |
def close(self): |
|
233 |
if self.__cnx is not None: |
|
234 |
self.__cnx.close() |
|
235 |
Delete(self.__record) |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1131
diff
changeset
|
236 |
|
0 | 237 |
def __save(self): |
238 |
if self.__is_dirty: |
|
239 |
self.__record['data'] = Blob(dumps(self.data)) |
|
240 |
Put(self.__record) |
|
241 |
self.__is_dirty = False |
|
242 |
||
243 |
def user(self, req=None, props=None): |
|
244 |
"""return the User object associated to this connection""" |
|
245 |
return self.__user |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1131
diff
changeset
|
246 |
|
0 | 247 |
|
248 |
import logging |
|
249 |
from cubicweb import set_log_methods |
|
250 |
set_log_methods(ConnectionProxy, logging.getLogger('cubicweb.web.goa.session')) |
|
251 |
||
252 |
||
253 |
from cubicweb.common.view import StartupView |
|
254 |
from cubicweb.web import application |
|
255 |
||
256 |
class SessionsCleaner(StartupView): |
|
257 |
id = 'cleansessions' |
|
742
99115e029dca
replaced most of __selectors__ assignments with __select__
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
669
diff
changeset
|
258 |
__select__ = none_rset() & match_user_groups('managers') |
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1131
diff
changeset
|
259 |
|
0 | 260 |
def call(self): |
261 |
# clean web session |
|
262 |
session_manager = application.SESSION_MANAGER |
|
263 |
nbclosed, remaining = session_manager.clean_sessions() |
|
264 |
self.w(u'<div class="message">') |
|
265 |
self.w(u'%s web sessions closed<br/>\n' % nbclosed) |
|
266 |
# clean repository sessions |
|
267 |
repo = self.config.repository(vreg=self.vreg) |
|
268 |
nbclosed = repo.clean_sessions() |
|
269 |
self.w(u'%s repository sessions closed<br/>\n' % nbclosed) |
|
270 |
self.w(u'%s remaining sessions<br/>\n' % remaining) |
|
271 |
self.w(u'</div>') |
|
669
5d2132832f03
start with explicit registration
sylvain.thenault@logilab.fr
parents:
635
diff
changeset
|
272 |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1131
diff
changeset
|
273 |
|
669
5d2132832f03
start with explicit registration
sylvain.thenault@logilab.fr
parents:
635
diff
changeset
|
274 |
def registration_callback(vreg): |
5d2132832f03
start with explicit registration
sylvain.thenault@logilab.fr
parents:
635
diff
changeset
|
275 |
vreg.register(SessionsCleaner) |
5d2132832f03
start with explicit registration
sylvain.thenault@logilab.fr
parents:
635
diff
changeset
|
276 |
vreg.register(GAEAuthenticationManager, clear=True) |
5d2132832f03
start with explicit registration
sylvain.thenault@logilab.fr
parents:
635
diff
changeset
|
277 |
vreg.register(GAEPersistentSessionManager, clear=True) |