Update of /cvsroot/jtoolkit/jToolkit/web
In directory sc8-pr-cvs1:/tmp/cvs-serv11292/web
Modified Files:
__init__.py safeapache.py server.py session.py
Log Message:
hate to do this, but a simple update of all the files from sjsoft for the meantime...
Index: __init__.py
===================================================================
RCS file: /cvsroot/jtoolkit/jToolkit/web/__init__.py,v
retrieving revision 1.2
retrieving revision 1.3
diff -C2 -d -r1.2 -r1.3
*** __init__.py 25 Aug 2003 12:16:45 -0000 1.2
--- __init__.py 25 Sep 2003 17:36:55 -0000 1.3
***************
*** 26,33 ****
--- 26,47 ----
servers = {}
+ import os, thread, time
+ logfilename = 'C:\\Temp\\threads.log'
+
+ def logtime(message):
+ osid = os.getpid()
+ threadid = thread.get_ident()
+ t = time.time()
+ ms = int((t - int(t))*1000.0)
+ timestr = time.strftime('%Y-%m-%d %H:%M:%S') + '.%03d' % ms
+ f = open(logfilename, 'a')
+ f.write('%s: pid %r tid %r: %s\n' % (timestr, osid, threadid, message))
+ f.close()
+
# handler is in here so that we can say PythonHandler jToolkit.web
# (modpython automatically looks for handler in that module)
def handler(req):
"""the standard handler which locates the instance, creates the server if neccessary, and hands off to it"""
+ logtime('handler start: ' + req.uri)
apache_options = req.get_options()
modulename = apache_options['jToolkit.module']
***************
*** 46,50 ****
servers[fullinstancename] = server
pathwords = filter(None, req.uri.split('/')) # split into bits, strip out empty strings
thepage = server.handle(req, pathwords)
! return server.sendpage(req, thepage)
--- 60,68 ----
servers[fullinstancename] = server
pathwords = filter(None, req.uri.split('/')) # split into bits, strip out empty strings
+ logtime('calling server.handle: ' + req.uri)
thepage = server.handle(req, pathwords)
! logtime('calling server.sendpage: ' + req.uri)
! result = server.sendpage(req, thepage)
! logtime('done: ' + req.uri)
! return result
Index: safeapache.py
===================================================================
RCS file: /cvsroot/jtoolkit/jToolkit/web/safeapache.py,v
retrieving revision 1.2
retrieving revision 1.3
diff -C2 -d -r1.2 -r1.3
*** safeapache.py 25 Aug 2003 12:16:45 -0000 1.2
--- safeapache.py 25 Sep 2003 17:36:55 -0000 1.3
***************
*** 53,73 ****
# fakereq is useful for testing in Python interpreter
fakereq = FakeRequest()
- util = FakeUtil()
- apache = FakeApache()
try:
from mod_python import apache
except:
! print "Can't import mod_python.apache; possibly not running within apache"
! e = sys.exc_info()
! print e[0], e[1]
! print "Simulating fake connection: this will not work on the web server"
! print
try:
from mod_python import util # for FieldStorage class
except:
! print "Can't import mod_python.util; possibly not running within apache"
! e = sys.exc_info()
! print e[0], e[1]
! print
--- 53,65 ----
# fakereq is useful for testing in Python interpreter
fakereq = FakeRequest()
try:
from mod_python import apache
except:
! apache = FakeApache()
!
try:
from mod_python import util # for FieldStorage class
except:
! util = FakeUtil()
Index: server.py
===================================================================
RCS file: /cvsroot/jtoolkit/jToolkit/web/server.py,v
retrieving revision 1.2
retrieving revision 1.3
diff -C2 -d -r1.2 -r1.3
*** server.py 25 Aug 2003 12:16:45 -0000 1.2
--- server.py 25 Sep 2003 17:36:55 -0000 1.3
***************
*** 150,181 ****
class AppServer(object):
"""base class for AppServers... handles requests. need to define getpage in subclass"""
! def __init__(self, instance, sessioncache, errorhandler=None, loginpageclass=LoginPage):
"""constructs a Server for a given instance, using the given session cache and error handler"""
self.instance = instance
! self.sessioncache = sessioncache
if errorhandler is None:
self.errorhandler = errors.ErrorHandler(instance)
else:
self.errorhandler = errorhandler
- if not hasattr(self.instance, 'db'):
- self.instance.db = database.dbwrapper(instance, self.errorhandler)
- if not hasattr(self.instance, 'checkshift'):
- self.instance.checkshift = self.checkshift
- self.loginpageclass = loginpageclass
self.languagelist = localize.getinstalledlanguages(self.instance.localedir)
self.languagenames = localize.getlanguagenames(self.languagelist)
self.translation = localize.translation(self.instance.localedomains, self.instance.localedir, self.languagelist)
! self.defaultlanguage = self.languagelist[0]
def handle(self, req, pathwords):
"""handles the request and returns a page object in response"""
argdict = self.processargs(self.instance, req)
! session = self.checklogin(req, argdict)
! if session.isopen:
! session.pagecount += 1
! session.remote_ip = req.connection.remote_ip
! return self.getpage(pathwords, session, argdict)
! else:
! return self.loginpageclass(session, argdict, languagenames=self.languagenames)
def sendpage(self, req, thepage):
--- 150,184 ----
class AppServer(object):
"""base class for AppServers... handles requests. need to define getpage in subclass"""
! def __init__(self, instance, sessioncache=None, errorhandler=None):
"""constructs a Server for a given instance, using the given session cache and error handler"""
self.instance = instance
! if sessioncache is None:
! self.sessioncache = session.SessionCache()
! else:
! self.sessioncache = sessioncache
if errorhandler is None:
self.errorhandler = errors.ErrorHandler(instance)
else:
self.errorhandler = errorhandler
self.languagelist = localize.getinstalledlanguages(self.instance.localedir)
self.languagenames = localize.getlanguagenames(self.languagelist)
self.translation = localize.translation(self.instance.localedomains, self.instance.localedir, self.languagelist)
! if hasattr(self.instance, 'defaultlanguage'):
! self.defaultlanguage = self.instance.defaultlanguage
! else:
! self.defaultlanguage = localize.getdefaultlanguage(self.languagelist)
def handle(self, req, pathwords):
"""handles the request and returns a page object in response"""
argdict = self.processargs(self.instance, req)
! session = self.getsession(req, argdict)
! session.pagecount += 1
! session.remote_ip = req.connection.remote_ip
! return self.getpage(pathwords, session, argdict)
!
! def getsession(self, req, argdict):
! """gets the session for the request"""
! session = self.sessioncache.getsession(req,self)
! return session
def sendpage(self, req, thepage):
***************
*** 190,194 ****
# return the html response (whether customized or standard)
req.send_http_header()
! req.write(response)
return safeapache.apache.OK
elif isinstance(thepage, Redirect):
--- 193,201 ----
# return the html response (whether customized or standard)
req.send_http_header()
! if type(response) == unicode:
! # TODO: get encoding from http request...
! req.write(response.encode('iso8859'))
! else:
! req.write(response)
return safeapache.apache.OK
elif isinstance(thepage, Redirect):
***************
*** 213,224 ****
if type(value) == list:
# this only happens with multiple arguments, which we don't want
! return value[0]
elif hasattr(value, 'value'):
# this is for a StringField from mod_python 3...
! return value.value
else:
! return value
! def checklogin(self, req, argdict):
"""checks login. if valid, return the requested page, otherwise return the login page"""
islogin = argdict.get("islogin",0)
--- 220,279 ----
if type(value) == list:
# this only happens with multiple arguments, which we don't want
! value = value[0]
elif hasattr(value, 'value'):
# this is for a StringField from mod_python 3...
! value = value.value
! if type(value) == str:
! return value.decode('iso8859')
! return value
! def gettranslation(self, language):
! """returns a translation object for the given language (or default if language is None)"""
! if language is None:
! return self.translation
else:
! languagelist = [language] + self.languagelist
! return localize.translation(self.instance.localedomains, self.instance.localedir, languagelist)
! def localize(self, message):
! """returns the localized form of a message"""
! # this is used when no session is available
! return self.translation.gettext(message)
!
! def initsession(self, session):
! """takes a new session and adds attributes we need"""
! pass
!
! class DBAppServer(AppServer):
! """basic App Server that also handles connection to the database..."""
! def __init__(self, instance, sessioncache=None, errorhandler=None):
! """constructs a Server for a given instance, using the given session cache and error handler"""
! super(DBAppServer, self).__init__(instance, sessioncache, errorhandler)
! self.instance = instance
! if not hasattr(self.instance, 'db'):
! self.instance.db = database.dbwrapper(instance, self.errorhandler)
!
! class LoginAppServer(DBAppServer):
! """AppServer that includes a login facility"""
! def __init__(self, instance, sessioncache=None, errorhandler=None, loginpageclass=LoginPage):
! """constructs a Server for a given instance, using the given session cache and error handler"""
! if sessioncache is None:
! sessioncache = session.SessionCache(sessionclass=session.LoginSession)
! super(LoginAppServer, self).__init__(instance, sessioncache, errorhandler)
! if not hasattr(self.instance, 'checkshift'):
! self.instance.checkshift = self.checkshift
! self.loginpageclass = loginpageclass
!
! def handle(self, req, pathwords):
! """handles the request and returns a page object in response"""
! argdict = self.processargs(self.instance, req)
! session = self.getsession(req, argdict)
! if session.isopen:
! session.pagecount += 1
! session.remote_ip = req.connection.remote_ip
! return self.getpage(pathwords, session, argdict)
! else:
! return self.loginpageclass(session, argdict, languagenames=self.languagenames)
!
! def getsession(self, req, argdict):
"""checks login. if valid, return the requested page, otherwise return the login page"""
islogin = argdict.get("islogin",0)
***************
*** 240,261 ****
return 1
! def initsession(self, session):
! """takes a new session and adds attributes we need"""
! pass
!
! def gettranslation(self, language):
! """returns a translation object for the given language (or default if language is None)"""
! if language is None:
! return self.translation
! else:
! languagelist = [language] + self.languagelist
! return localize.translation(self.instance.localedomains, self.instance.localedir, languagelist)
!
! def localize(self, message):
! """returns the localized form of a message"""
! # this is used when no session is available
! return self.translation.gettext(message)
!
! class MultiAppServer(AppServer):
"""serves multiple instances in subdirectories..."""
def __init__(self, instance, sessioncache=None, errorhandler=None, loginpageclass=LoginPage):
--- 295,299 ----
return 1
! class MultiAppServer(LoginAppServer):
"""serves multiple instances in subdirectories..."""
def __init__(self, instance, sessioncache=None, errorhandler=None, loginpageclass=LoginPage):
***************
*** 325,329 ****
return widgets.Page(session.localize("Select Application"), links)
! class SharedLoginAppServer(AppServer):
"""allows instance to be passed a shared session..."""
def handle(self, req, pathwords, sharedsession=None):
--- 363,367 ----
return widgets.Page(session.localize("Select Application"), links)
! class SharedLoginAppServer(LoginAppServer):
"""allows instance to be passed a shared session..."""
def handle(self, req, pathwords, sharedsession=None):
***************
*** 331,335 ****
argdict = self.processargs(self.instance, req)
exitapp = argdict.get('exitapp', 0)
! session = self.checklogin(req, argdict, sharedsession)
if exitapp:
return Redirect("../index.html")
--- 369,373 ----
argdict = self.processargs(self.instance, req)
exitapp = argdict.get('exitapp', 0)
! session = self.getsession(req, argdict, sharedsession)
if exitapp:
return Redirect("../index.html")
***************
*** 341,345 ****
return self.loginpageclass(session, argdict, languagenames=self.languagenames)
! def checklogin(self, req, argdict, sharedsession):
"""checks login. if valid, return the requested page, otherwise return the login page"""
islogin = argdict.get("islogin",0)
--- 379,383 ----
return self.loginpageclass(session, argdict, languagenames=self.languagenames)
! def getsession(self, req, argdict, sharedsession):
"""checks login. if valid, return the requested page, otherwise return the login page"""
islogin = argdict.get("islogin",0)
***************
*** 347,351 ****
islogout = argdict.get("islogout",0)
manualmode = islogin or confirmlogin or islogout
! session = super(SharedLoginAppServer, self).checklogin(req, argdict)
if not (manualmode or session.isopen) and sharedsession is not None and sharedsession.isopen:
sharedsession.sharelogindetails(req, session)
--- 385,389 ----
islogout = argdict.get("islogout",0)
manualmode = islogin or confirmlogin or islogout
! session = super(SharedLoginAppServer, self).getsession(req, argdict)
if not (manualmode or session.isopen) and sharedsession is not None and sharedsession.isopen:
sharedsession.sharelogindetails(req, session)
***************
*** 358,362 ****
"""constructs the multi-app server"""
if sessioncache is None:
! sessioncache = session.SessionCache(sessioncookiename=instance.__name__+'session')
super(SharedLoginMultiAppServer, self).__init__(instance, sessioncache, errorhandler, loginpageclass)
self.instances = self.instance.instances
--- 396,400 ----
"""constructs the multi-app server"""
if sessioncache is None:
! sessioncache = session.SessionCache(sessionclass=LoginSession,sessioncookiename=instance.__name__+'session')
super(SharedLoginMultiAppServer, self).__init__(instance, sessioncache, errorhandler, loginpageclass)
self.instances = self.instance.instances
***************
*** 385,389 ****
else:
argdict = self.processargs(self.instance, req)
! session = self.checklogin(req, argdict)
if session.isopen:
session.pagecount += 1
--- 423,427 ----
else:
argdict = self.processargs(self.instance, req)
! session = self.getsession(req, argdict)
if session.isopen:
session.pagecount += 1
***************
*** 403,410 ****
return widgets.Page(session.localize("Select Application"), [status, links])
! def checklogin(self, req, argdict):
"""checks login. if valid, return the requested page, otherwise return the login page"""
islogin = argdict.get("islogin",0)
! session = super(SharedLoginMultiAppServer, self).checklogin(req, argdict)
# remember the password so we can give it to other sessions...
if islogin and session.isopen:
--- 441,448 ----
return widgets.Page(session.localize("Select Application"), [status, links])
! def getsession(self, req, argdict):
"""checks login. if valid, return the requested page, otherwise return the login page"""
islogin = argdict.get("islogin",0)
! session = super(SharedLoginMultiAppServer, self).getsession(req, argdict)
# remember the password so we can give it to other sessions...
if islogin and session.isopen:
***************
*** 422,427 ****
if pathwords[0] in self.instances:
session = self.sessioncache.getsession(req, self)
! if session.isopen:
! return self.handledefer(req, pathwords, session)
else:
return None
--- 460,464 ----
if pathwords[0] in self.instances:
session = self.sessioncache.getsession(req, self)
! return self.handledefer(req, pathwords, session)
else:
return None
***************
*** 429,433 ****
argdict = self.processargs(self.instance, req)
exitapp = argdict.get('exitapp', 0)
! session = self.checklogin(req, argdict, sharedsession)
if exitapp:
return Redirect("../index.html")
--- 466,470 ----
argdict = self.processargs(self.instance, req)
exitapp = argdict.get('exitapp', 0)
! session = self.getsession(req, argdict, sharedsession)
if exitapp:
return Redirect("../index.html")
Index: session.py
===================================================================
RCS file: /cvsroot/jtoolkit/jToolkit/web/session.py,v
retrieving revision 1.2
retrieving revision 1.3
diff -C2 -d -r1.2 -r1.3
*** session.py 25 Aug 2003 12:16:45 -0000 1.2
--- session.py 25 Sep 2003 17:36:55 -0000 1.3
***************
*** 139,143 ****
self.setcookie(req, cookiedict)
! class Session:
"""represents a user session"""
def __init__(self, sessioncache, server, sessionstring = None):
--- 139,143 ----
self.setcookie(req, cookiedict)
! class Session(object):
"""represents a user session"""
def __init__(self, sessioncache, server, sessionstring = None):
***************
*** 145,149 ****
self.server = server
self.instance = server.instance
- self.db = server.instance.db
self.parentsessionname = ""
self.childsessions = {}
--- 145,148 ----
***************
*** 158,168 ****
# allow the server to add any attributes it requires
server.initsession(self)
! if sessionstring is not None:
! # split up the sessionstring into components
! if sessionstring.count(':') >= 3:
! self.username,self.timestamp,self.sessionid,self.parentsessionname = sessionstring.split(':',3)
! # make sure this is valid, and open it...
! self.validate()
! self.open()
def getstatus(self):
--- 157,161 ----
# allow the server to add any attributes it requires
server.initsession(self)
! self.setsessionstring(sessionstring)
def getstatus(self):
***************
*** 216,220 ****
"""check the login status (auto logoff etc)"""
if self.isopen:
! self.status = self.localize("logged in as <b>%s</b>") % (self.username)
self.updatelastused()
--- 209,213 ----
"""check the login status (auto logoff etc)"""
if self.isopen:
! self.status = self.localize("connected")
self.updatelastused()
***************
*** 223,236 ****
return dates.nosepdateparser.parse(self.timestamp)
- def getsessionid(self, password):
- """returns the hex sessionid for the session, using the password"""
- md5password = md5hexdigest(password)
- return md5hexdigest(self.username+':'+self.timestamp+':'+md5password+':'+self.instance.sessionkey+':'+self.server.name)
-
def getsessionstring(self):
"""creates the full session string using the sessionid"""
! sessionstring = self.username+':'+self.timestamp+':'+self.sessionid+':'+self.parentsessionname
return sessionstring
def updatecookie(self, req, server):
"""update session string in cookie in req to reflect whether session is open"""
--- 216,234 ----
return dates.nosepdateparser.parse(self.timestamp)
def getsessionstring(self):
"""creates the full session string using the sessionid"""
! sessionstring = self.timestamp+':'+self.sessionid
return sessionstring
+ def setsessionstring(self, sessionstring):
+ """sets the session string for this session"""
+ if sessionstring is not None:
+ # split up the sessionstring into components
+ if sessionstring.count(':') >= 1:
+ self.timestamp,self.sessionid = sessionstring.split(':',1)
+ # make sure this is valid, and open it...
+ self.validate()
+ self.open()
+
def updatecookie(self, req, server):
"""update session string in cookie in req to reflect whether session is open"""
***************
*** 239,276 ****
else:
self.sessioncache.setsessioncookie(req, server, '-')
-
- def create(self,username,password,timestamp,language):
- """initializes the session with the parameters"""
- self.username, password, self.timestamp = username.lower(), password.lower(), timestamp
- self.setlanguage(language)
- self.sessionid = self.getsessionid(password)
- self.validate()
- self.open()
-
- def sharelogindetails(self, req, othersession):
- """shares this session's login details with othersession"""
- username = self.username
- # this expects that self.password exist ... see SharedLoginMultiAppServer.checklogin...
- password = getattr(self, 'password', '')
- language = self.language
- timestamp = dates.currentdate().Format('%Y%m%d%H%M%S')
- # currently assumes we do not need to close the other session
- otherusername = getattr(othersession, 'username', '')
- othersession.parentsessionname = self.server.name
- othersession.create(username, password, timestamp, language)
- if othersession.isopen:
- othersession.updatecookie(req, othersession.server)
- self.childsessions[othersession.server.name] = othersession
- else:
- othersession.close(req)
- othersession.parentsessionname = ""
- othersession.username = otherusername
- othersession.status = ""
-
- def invalidatechild(self, childname):
- """logs out of a child session"""
- childsession = self.childsessions.get(childname, 0)
- if childsession:
- childsession.markinvalid()
def markinvalid(self):
--- 237,240 ----
***************
*** 283,303 ****
self.isopen = 0
! def confirmlogin(self, req, username, password, timestamp):
! """validates a username and password for an already-established session"""
! username, password = username.lower(), password.lower()
! if not self.isvalid:
! # create a new session
! self.create(username, password, timestamp, self.language)
! if self.isopen:
! self.updatecookie(req, self.server)
else:
! # validate the old session...
! if username != self.username:
! self.close(req)
! self.status = self.localize("failed login confirmation")
! self.sessionid = self.getsessionid(password)
! if not self.validate():
! self.close(req)
! self.status = self.localize("failed login confirmation")
def validate(self):
--- 247,291 ----
self.isopen = 0
! def validate(self):
! """checks if this session is valid"""
! self.isvalid = 1
! return 1
!
! def checksessionid(self):
! """returns the hex sessionid for the session, using the password"""
! correctsessionid = self.timestamp+':'+md5hexdigest(self.timestamp)
! return correctsessionid == self.sessionid
!
! def setlanguage(self, language):
! """sets the language for the session"""
! if language is None:
! self.language = self.server.defaultlanguage
else:
! self.language = language
! self.translation = self.server.gettranslation(self.language)
!
! def localize(self, message):
! """returns the localized form of a message"""
! return self.translation.gettext(message)
!
! class LoginSession(Session):
! """A session that allows login based on a database"""
! def __init__(self, sessioncache, server, sessionstring = None):
! self.db = server.instance.db
! super(LoginSession, self).__init__(sessioncache, server, sessionstring)
!
! def open(self):
! """tries to open the given session, returns success"""
! self.isopen = 0
! super(LoginSession, self).open()
! if self.isopen:
! self.status = self.localize("logged in as <b>%s</b>") % self.username
! return self.isopen
!
! def checkstatus(self, req):
! """check the login status (auto logoff etc)"""
! if self.isopen:
! self.status = self.localize("logged in as <b>%s</b>") % (self.username)
! self.updatelastused()
def validate(self):
***************
*** 313,316 ****
--- 301,309 ----
return self.isvalid
+ def getsessionid(self, password):
+ """returns the hex sessionid for the session, using the password"""
+ md5password = md5hexdigest(password)
+ return md5hexdigest(self.username+':'+self.timestamp+':'+md5password+':'+self.instance.sessionkey+':'+self.server.name)
+
def checksessionid(self):
"""returns the hex sessionid for the session, using the password"""
***************
*** 320,323 ****
--- 313,332 ----
return correctsessionid == self.sessionid
+ def getsessionstring(self):
+ """creates the full session string using the sessionid"""
+ sessionstring = self.username+':'+self.timestamp+':'+self.sessionid+':'+self.parentsessionname
+ return sessionstring
+
+ def setsessionstring(self, sessionstring):
+ """sets the session string for this session"""
+ # split up the sessionstring into components
+ if sessionstring is not None:
+ # split up the sessionstring into components
+ if sessionstring.count(':') >= 3:
+ self.username,self.timestamp,self.sessionid,self.parentsessionname = sessionstring.split(':',3)
+ # make sure this is valid, and open it...
+ self.validate()
+ self.open()
+
def getmd5password(self, username=None):
"""retrieves the md5 hash of the password for this user, or another if another is given..."""
***************
*** 344,359 ****
count = int(q.fetchone()[0])
return count > 0
! def setlanguage(self, language):
! """sets the language for the session"""
! if language is None:
! self.language = self.server.defaultlanguage
else:
! self.language = language
! self.translation = self.server.gettranslation(language)
! def localize(self, message):
! """returns the localized form of a message"""
! return self.translation.gettext(message)
--- 353,407 ----
count = int(q.fetchone()[0])
return count > 0
+
+ def create(self,username,password,timestamp,language):
+ """initializes the session with the parameters"""
+ self.username, password, self.timestamp = username.lower(), password.lower(), timestamp
+ self.setlanguage(language)
+ self.sessionid = self.getsessionid(password)
+ self.validate()
+ self.open()
! def sharelogindetails(self, req, othersession):
! """shares this session's login details with othersession"""
! username = self.username
! # this expects that self.password exist ... see SharedLoginMultiAppServer.checklogin...
! password = getattr(self, 'password', '')
! language = self.language
! timestamp = dates.currentdate().Format('%Y%m%d%H%M%S')
! # currently assumes we do not need to close the other session
! otherusername = getattr(othersession, 'username', '')
! othersession.parentsessionname = self.server.name
! othersession.create(username, password, timestamp, language)
! if othersession.isopen:
! othersession.updatecookie(req, othersession.server)
! self.childsessions[othersession.server.name] = othersession
else:
! othersession.close(req)
! othersession.parentsessionname = ""
! othersession.username = otherusername
! othersession.status = ""
! def invalidatechild(self, childname):
! """logs out of a child session"""
! childsession = self.childsessions.get(childname, 0)
! if childsession:
! childsession.markinvalid()
+ def confirmlogin(self, req, username, password, timestamp):
+ """validates a username and password for an already-established session"""
+ username, password = username.lower(), password.lower()
+ if not self.isvalid:
+ # create a new session
+ self.create(username, password, timestamp, self.language)
+ if self.isopen:
+ self.updatecookie(req, self.server)
+ else:
+ # validate the old session...
+ if username != self.username:
+ self.close(req)
+ self.status = self.localize("failed login confirmation")
+ self.sessionid = self.getsessionid(password)
+ if not self.validate():
+ self.close(req)
+ self.status = self.localize("failed login confirmation")
|