[dataimport] drop duplicate init of MassiveObjectStore.sql
# copyright 2003-2014 LOGILAB S.A. (Paris, FRANCE), all rights reserved.# contact http://www.logilab.fr/ -- mailto:contact@logilab.fr## This file is part of CubicWeb.## CubicWeb is free software: you can redistribute it and/or modify it under the# terms of the GNU Lesser General Public License as published by the Free# Software Foundation, either version 2.1 of the License, or (at your option)# any later version.## CubicWeb is distributed in the hope that it will be useful, but WITHOUT# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more# details.## You should have received a copy of the GNU Lesser General Public License along# with CubicWeb. If not, see <http://www.gnu.org/licenses/>."""web session: by default the session is actually the db connection """__docformat__="restructuredtext en"fromtimeimporttimefromloggingimportgetLoggerfromlogilab.common.registryimportRegistrableObjectfromcubicwebimportRepositoryError,Unauthorized,BadConnectionId,set_log_methodsfromcubicweb.predicatesimportyesfromcubicweb.webimportInvalidSessionfromcubicweb.web.viewsimportauthenticationclassAbstractSessionManager(RegistrableObject):"""manage session data associated to a session identifier"""__abstract__=True__select__=yes()__registry__='sessions'__regid__='sessionmanager'def__init__(self,repo):vreg=repo.vregself.session_time=vreg.config['http-session-time']orNoneself.authmanager=authentication.RepositoryAuthenticationManager(repo)interval=(self.session_timeor0)/2.ifvreg.config.anonymous_user()[0]isnotNone:self.cleanup_anon_session_time=vreg.config['cleanup-anonymous-session-time']or5*60assertself.cleanup_anon_session_time>0ifself.session_timeisnotNone:self.cleanup_anon_session_time=min(self.session_time,self.cleanup_anon_session_time)interval=self.cleanup_anon_session_time/2.# we don't want to check session more than once every 5 minutesself.clean_sessions_interval=max(5*60,interval)defclean_sessions(self):"""cleanup sessions which has not been unused since a given amount of time. Return the number of sessions which have been closed. """self.debug('cleaning http sessions')session_time=self.session_timeclosed,total=0,0forsessioninself.current_sessions():total+=1last_usage_time=session.mtimeno_use_time=(time()-last_usage_time)ifsession.anonymous_session:ifno_use_time>=self.cleanup_anon_session_time:self.close_session(session)closed+=1elifsession_timeisnotNoneandno_use_time>=session_time:self.close_session(session)closed+=1returnclosed,total-closeddefcurrent_sessions(self):"""return currently open sessions"""raiseNotImplementedError()defget_session(self,req,sessionid):"""return existing session for the given session identifier"""raiseNotImplementedError()defopen_session(self,req):"""open and return a new session for the given request. raise :exc:`cubicweb.AuthenticationError` if authentication failed (no authentication info found or wrong user/password) """raiseNotImplementedError()defclose_session(self,session):"""close session on logout or on invalid session detected (expired out, corrupted...) """raiseNotImplementedError()set_log_methods(AbstractSessionManager,getLogger('cubicweb.sessionmanager'))classInMemoryRepositorySessionManager(AbstractSessionManager):"""manage session data associated to a session identifier"""def__init__(self,*args,**kwargs):super(InMemoryRepositorySessionManager,self).__init__(*args,**kwargs)# XXX require a RepositoryAuthenticationManager which violates# authenticate interface by returning a session instead of a user#assert isinstance(self.authmanager, RepositoryAuthenticationManager)self._sessions={}# dump_data / restore_data to avoid loosing open sessions on registry# reloadingdefdump_data(self):returnself._sessionsdefrestore_data(self,data):self._sessions=datadefcurrent_sessions(self):returnself._sessions.values()defget_session(self,req,sessionid):"""return existing session for the given session identifier"""ifsessionidnotinself._sessions:raiseInvalidSession()session=self._sessions[sessionid]try:user=self.authmanager.validate_session(req,session)exceptInvalidSession:self.close_session(session)raiseifsession.closed:self.close_session(session)raiseInvalidSession()returnsessiondefopen_session(self,req):"""open and return a new session for the given request. The session is also bound to the request. raise :exc:`cubicweb.AuthenticationError` if authentication failed (no authentication info found or wrong user/password) """session,login=self.authmanager.authenticate(req)self._sessions[session.sessionid]=sessionsession.mtime=time()returnsessiondefpostlogin(self,req,session):"""postlogin: the user have been related to a session Both req and session are passed to this function because actually linking the request to the session is not yet done and not the responsability of this object. """# Update last connection date# XXX: this should be in a post login hook in the repository, but there# we can't differentiate actual login of automatic session# reopening. Is it actually a problem?if'last_login_time'inreq.vreg.schema:self._update_last_login_time(session)req.set_message(req._('welcome %s!')%session.user.login)def_update_last_login_time(self,session):# XXX should properly detect missing permission / non writeable source# and avoid "except (RepositoryError, Unauthorized)" belowtry:withsession.new_cnx()ascnx:cnx.execute('SET X last_login_time NOW WHERE X eid %(x)s',{'x':session.user.eid})cnx.commit()except(RepositoryError,Unauthorized):passdefclose_session(self,session):"""close session on logout or on invalid session detected (expired out, corrupted...) """self.info('closing http session %s'%session.sessionid)self._sessions.pop(session.sessionid,None)ifnotsession.closed:session.repo.close(session.sessionid)