[Hepserver-commits] hep/hep/services __init__.py,NONE,1.1 authenticator.py,NONE,1.1 datamanager.py,N
Status: Alpha
Brought to you by:
abefettig
|
From: <abe...@us...> - 2003-07-10 16:47:26
|
Update of /cvsroot/hepserver/hep/hep/services
In directory sc8-pr-cvs1:/tmp/cvs-serv6713/hep/services
Added Files:
__init__.py authenticator.py datamanager.py http.py imap.py
Log Message:
imported files
--- NEW FILE: __init__.py ---
pass
--- NEW FILE: authenticator.py ---
from twisted.cred import credentials
from twisted.cred.error import UnauthorizedLogin
from twisted.cred import checkers, portal
from twisted.internet import defer, app
import os.path
class Service(app.ApplicationService):
NAME = 'Authenticator'
def startService(self):
realm = self.serviceParent.getServiceNamed('Data Manager')
self.portal = portal.Portal(realm)
passwordFileName = os.path.join(self.serviceParent.dataPath, 'passwd')
self.portal.registerChecker(PasswordAuthenticator(passwordFileName))
self.portal.registerChecker(checkers.AllowAnonymousAccess())
class PasswordAuthenticator:
__implements__ = checkers.ICredentialsChecker
credentialInterfaces = credentials.IUsernamePassword,
def __init__(self, passwordFileName):
self.passwords = {}
passwordFile = open(passwordFileName)
userLines = passwordFile.readlines()
for listing in userLines:
userName, password = listing.strip().split(":")
self.passwords[userName] = password
def requestAvatarId(self, credentials):
if self.passwords.get(credentials.username) == credentials.password:
return defer.succeed(credentials.username)
else:
return defer.fail(UnauthorizedLogin())
--- NEW FILE: datamanager.py ---
import os
import os.path
import urllib
import cPickle as pickle
import time
import messaging
from messaging.url import Url
import messaging.cache
from twisted.internet import reactor, defer
from twisted.internet.defer import maybeDeferred
import twisted.python.log
twisted.python.log.logfile = messaging.log
from hep import connection
from twisted.internet.app import ApplicationService
from messaging.protocols.file import MaildirStore
from twisted.cred.portal import IRealm
class DataManagerService(ApplicationService):
NAME = 'Data Manager'
__implements__ = IRealm
def startService(self):
dataDir = self.serviceParent.dataPath
self.connections = {}
self.avatarInterfaces = {}
self.avatarInterfaces[HepUser] = HepUserWrapper
# make sure dataDir has the sub-folders and files that it should
userDir = os.path.join(dataDir, 'users')
if not os.path.exists(userDir): os.makedirs(userDir)
self.cacheDir = os.path.join(dataDir, "cache")
if not os.path.exists(self.cacheDir): os.makedirs(self.cacheDir)
passwordFileName = os.path.join(dataDir, "passwd")
if not os.path.isfile(passwordFileName):
# create the file.
open(passwordFile, 'w').close()
self.connector = messaging.Connector()
self.connector.cachePath = self.cacheDir
self.users = {}
for userName in os.listdir(os.path.join(dataDir, 'users')):
userDir = os.path.join(dataDir, 'users', userName)
# make sure the user folder has the neccessary sub-folders
for path in ('messages/local', 'messages/connections', 'messages/index'):
fullPath = os.path.join(*([userDir] + path.split('/')))
if not os.path.exists(fullPath):
os.makedirs(fullPath)
self.users[userName] = HepUser(userDir, self.cacheDir, userName)
reactor.callLater(0, self.loadConnections)
def requestAvatar(self, avatarID, mind, *interfaces):
# rudely ignore the requested interface - always return a HepUser object
# FIXME (yawn...)
for iface in interfaces:
if iface in self.avatarInterfaces:
avatar = maybeDeferred(self.avatarInterfaces[iface], self.users.get(avatarID))
avatar.addCallback(lambda a: (iface, a, lambda: None))
return avatar
else:
raise NotImplementedError("no interface")
def loadConnections(self):
for user in self.users.values():
for connection in user.connections.values():
if self.connections.has_key(str(connection.url)):
user.messages.connectionStore.childFolders[connection.name] = self.connections[str(connection.url)]
d = self.connector.openUrl(connection.url)
d.addCallback(self.gotConnection, connection, user)
def gotConnection(self, store, connection, user):
self.connections[str(connection.url)] = store
user.messages.connectionStore.childFolders[connection.name] = store
user.messages.connectionStore.childFolders[connection.name].name = connection.name
class RootMessageStore(MaildirStore):
"""
A message store used for organizing child stores only.
It contains a number of MaildirStores, plus 'connections'
"""
canPost = 0
canEdit = 0
canDelete = 0
def __init__(self, url, connections):
MaildirStore.__init__(self, url)
self.name = ''
self.connectionStore = connections
def listChildFolders(self):
return MaildirStore.listChildFolders(self).addCallback(lambda names: names + ['Connections'])
def openChildFolder(self, folderName):
if folderName == 'Connections':
return defer.succeed(self.connectionStore)
else:
return MaildirStore.openChildFolder(self, folderName)
class HepUser:
def __init__(self, baseFolder, cacheFolder, username):
self.name = username
self.baseFolder = baseFolder
self.connector = messaging.Connector()
#self.index = search.MessageIndex(os.path.join(baseFolder,'messages','index'))
self.config = {}
self.connections = {}
connectionStore = messaging.MessageStore()
connectionStore.name = 'Connections'
mailboxPath = os.path.join(self.baseFolder, 'messages', 'local')
self.messages = RootMessageStore(Url(mailboxPath), connectionStore)
self.loadConfig()
self.loadConnections()
def loadConnections(self):
for connection in self.connections.values():
del(connection)
self.connections = {}
datafilePath = os.path.join(self.baseFolder, 'connections.dat')
if os.path.exists(datafilePath):
try: connections = pickle.load(file(datafilePath))
except:
print "ERROR LOADING CONNECTIONS FOR USER %s!!!" % self.name
connections = []
for connection in connections:
self.connections[str(connection.name)] = connection
def saveConnections(self):
datafile = open(os.path.join(self.baseFolder, 'connections.dat'),'w')
pickle.dump(self.connections, datafile)
datafile.close()
def loadConfig(self):
try:
datafile = open(os.path.join(self.baseFolder, 'config.dat'),'r')
self.connector.preferences = pickle.load(datafile)
datafile.close()
except: pass
def saveConfig(self):
datafile = open(os.path.join(self.baseFolder, 'config.dat'),'w')
pickle.dump(self.connector.preferences, datafile)
datafile.close()
def HepUserWrapper(user):
return user
--- NEW FILE: http.py ---
from twisted.web import server, static, resource
from twisted.internet import app, reactor
import hep.web
from hep.web.messages import MessagesPage
from hep.web.models import UserModel
from twisted.python.util import sibpath
class Service(app.ApplicationService):
PORT = 5080
NAME = 'HTTP'
def startService(self):
# register an IResource interface with the data manager
dm = self.serviceParent.getServiceNamed('Data Manager')
dm.avatarInterfaces[resource.IResource] = getResource
self.factory = getFactory(self.serviceParent)
reactor.listenTCP(self.PORT, self.factory)
def getFactory(app):
portal = app.getServiceNamed('Authenticator').portal
res = resource.Resource()
site = server.Site(res)
# add static paths
for staticPath in ('images', 'styles'):
res.putChild(staticPath, static.File(sibpath(hep.web.__file__, staticPath)))
res.putChild("", static.Data("<html><a href='messages'>Messages</a>", "text/html"))
from twisted.web.woven.guard import UsernamePasswordWrapper, SessionWrapper
res.putChild("messages", SessionWrapper(UsernamePasswordWrapper(portal)))
return site
def getResource(user):
if user:
return MessagesPage(UserModel(user=user))
else:
return static.Data("anonymous browsing - <a href='perspective-init'>login</a>", "text/html")
--- NEW FILE: imap.py ---
"""
imap support for Hep.
"""
from twisted.protocols import imap4
from twisted.internet.app import ApplicationService
from twisted.internet.protocol import Factory
from twisted.internet import reactor, defer
from twisted.python import components
class Service(ApplicationService):
PORT = 5143
NAME = 'IMAP'
def startService(self):
# add support for getting IMAP accounts out of the datamanager service
dm = self.serviceParent.getServiceNamed('Data Manager')
dm.avatarInterfaces[imap4.IAccount] = openAccount
portal = self.serviceParent.getServiceNamed('Authenticator').portal
self.factory = IMAPFactory(portal)
self.factory.app = self.serviceParent
self.factory.protocol = HepIMAPServer
reactor.listenTCP(self.PORT, self.factory)
class IMAPFactory(Factory):
def __init__(self, portal):
self.portal = portal
def buildProtocol(self, address):
p = self.protocol()
p.portal = self.portal
p.factory = self
return p
class HepIMAPServer(imap4.IMAP4Server):
pass
def openAccount(user):
account = HepAccount(user)
return account.loadMailboxes()
class HepAccount(components.Adapter):
__implements = (imap4.IAccount,)
def loadMailboxes(self):
self.mailboxes = []
d = defer.Deferred()
listing = self.original.messages.openChildStores()
listing.addCallback(self.finishedLoadingMailboxes, d)
return d
def listMailboxes(self, ref, wildcard):
return self.mailboxes
def finishedLoadingMailboxes(self, stores, d):
results = []
for path, store in stores.items():
self.mailboxes.append([path, Mailbox(store)])
d.callback(self)
def create(self, path):
raise imap4.MailboxException("Permission denied")
def isSubscribed(self, path):
return 0
def subscribe(self, path):
return 1
class Mailbox(components.Adapter):
__implements__ = (imap4.IMailbox,)
def getHierarchicalDelimiter(self):
return '/'
def getFlags(self):
return []
|