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