Here are the examples of the python api twisted.cred.portal.Portal taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
92 Examples
3
Example 1
Project: ldaptor Source File: main.py
def getResource(cfg=None, skinFactory=None):
"""Get a resource for the Ldaptor-webui app."""
if cfg is None:
cfg = LDAPConfig()
checker = LDAPBindingChecker(cfg)
realm = TODOGetRidOfMeRealm(config=cfg)
porta = portal.Portal(realm)
porta.registerChecker(checkers.AllowAnonymousAccess(), credentials.IAnonymous)
porta.registerChecker(checker)
mainResource = guard.SessionWrapper(porta)
if skinFactory is None:
skinFactory = defskin.DefaultSkin
return skin.Skinner(skinFactory, mainResource)
3
Example 2
Project: SubliminalCollaborator Source File: test_service.py
def setUp(self):
self.realm = service.InMemoryWordsRealm("realmname")
self.checker = checkers.InMemoryUsernamePasswordDatabaseDontUse()
self.portal = portal.Portal(self.realm, [self.checker])
self.factory = service.IRCFactory(self.realm, self.portal)
c = []
for nick in self.STATIC_USERS:
c.append(self.realm.createUser(nick))
self.checker.addUser(nick.encode('ascii'), nick + "_password")
return DeferredList(c)
3
Example 3
def _makeConchFactory(self):
"""
Make a L{ConchTestServerFactory}, which allows us to start a
L{ConchTestServer} -- i.e. an actually listening conch.
"""
realm = ConchTestRealm()
p = portal.Portal(realm)
p.registerChecker(ConchTestPublicKeyChecker())
factory = ConchTestServerFactory()
factory.portal = p
return factory
3
Example 4
Project: leap_mail Source File: imap.py
def __init__(self, soledad_sessions, *args, **kw):
LEAPIMAPServer.__init__(self, *args, **kw)
realm = LocalSoledadIMAPRealm(soledad_sessions)
portal = Portal(realm)
checker = IMAPTokenChecker(soledad_sessions)
self.checker = checker
self.portal = portal
portal.registerChecker(checker)
3
Example 5
Project: mythbox Source File: test_newcred.py
def setUp(self):
dbfile = self.mktemp()
self.db = checkers.FilePasswordDB(dbfile, hash=self.hash)
f = file(dbfile, 'w')
for (u, p) in self.users:
f.write('%s:%s\n' % (u, crypt(p, u[:2])))
f.close()
r = TestRealm()
self.port = portal.Portal(r)
self.port.registerChecker(self.db)
3
Example 6
Project: frikanalen Source File: ftp_server.py
def start_ftp(port, root):
from twisted.internet import reactor
checker = djangoauth.DjangoAuthChecker()
realm = UploadFTPRealm("")
realm.root = root
fkportal = portal.Portal(realm, [checker])
ftpfactory = UploadFTPFactory(portal=fkportal)
reactor.listenTCP(port, ftpfactory)
3
Example 7
def __init__(self):
service.MultiService.__init__(self)
# Domains and portals for "client" protocols - POP3, IMAP4, etc
self.domains = DomainWithDefaultDict({}, BounceDomain())
self.portals = {}
self.monitor = FileMonitoringService()
self.monitor.setServiceParent(self)
self.smtpPortal = cred.portal.Portal(self)
3
Example 8
def getService(self):
r = Realm()
p = portal.Portal(r)
f = protocol.ServerFactory()
f.canaryservice = self
f.logger = self.logger
f.banner = self.banner
f.protocol = lambda: TelnetTransport(AlertAuthTelnetProtocol, p)
return internet.TCPServer(self.port, f, interface=self.listen_addr)
3
Example 9
Project: txjsonrpc Source File: auth.py
def wrapResource(resource, checkers, credFactories=[], realmName=""):
defaultCredFactory = guard.BasicCredentialFactory(realmName)
credFactories.insert(0, defaultCredFactory)
realm = HTTPAuthRealm(resource)
portal = Portal(realm, checkers)
return guard.HTTPAuthSessionWrapper(portal, credFactories)
3
Example 10
Project: flumotion Source File: test_pbstream.py
def startServer(self, immediateStop=False):
server = Server(immediateStop)
server.start()
p = portal.Portal(Dispatcher(server))
p.registerChecker(checkers.InMemoryUsernamePasswordDatabaseDontUse(
admin="pass", client="pass"))
self.serverPort = reactor.listenTCP(0, pb.PBServerFactory(p))
self.portno = self.serverPort.getHost().port
return server
3
Example 11
Project: kivy-remote-shell Source File: main.py
def getManholeFactory(namespace, **passwords):
realm = manhole_ssh.TerminalRealm()
def getManhole(_):
return manhole.ColoredManhole(namespace)
realm.chainedProtocolFactory.protocolFactory = getManhole
p = portal.Portal(realm)
p.registerChecker(
checkers.InMemoryUsernamePasswordDatabaseDontUse(**passwords))
f = manhole_ssh.ConchFactory(p)
return f
3
Example 12
def setUp(self):
self.proxy = sip.RegisterProxy(host="intarweb.us")
self.proxy.authorizers = self.proxy.authorizers.copy()
self.proxy.authorizers['digest'] = FakeDigestAuthorizer()
self.registry = FakeRegistry("intarweb.us")
self.proxy.registry = self.proxy.locator = self.registry
self.transport = proto_helpers.FakeDatagramTransport()
self.proxy.transport = self.transport
r = TestRealm()
p = cred.portal.Portal(r)
c = cred.checkers.InMemoryUsernamePasswordDatabaseDontUse()
c.addUser('[email protected]', 'password')
p.registerChecker(c)
self.proxy.portal = p
3
Example 13
Project: django-conch Source File: conch.py
def make_service(args):
checker = DjangoSuperuserCredChecker()
def chainProtocolFactory():
return insults.ServerProtocol(
args['protocol_factory'],
*args.get('protocol_args', ()),
**args.get('protocol_kwargs', {}))
realm = TerminalRealm()
realm.chainedProtocolFactory = chainProtocolFactory
ptl = portal.Portal(realm, [checker])
f = ConchFactory(ptl)
return internet.TCPServer(args['ssh_port'], f)
3
Example 14
def __init__(self, soledad_sessions, keymanager_sessions, sendmail_opts,
encrypted_only=False):
realm = LocalSMTPRealm(
keymanager_sessions, soledad_sessions, sendmail_opts,
encrypted_only)
portal = Portal(realm)
checker = SMTPTokenChecker(soledad_sessions)
self.checker = checker
self.portal = portal
portal.registerChecker(checker)
3
Example 15
def getService(self):
p = Portal(FTPRealm(FTP_PATH), [DenyAllAccess()])
f = FTPFactory(p)
f.protocol = LoggingFTP
f.welcomeMessage = self.banner
f.canaryservice = self
return internet.TCPServer(self.port, f, interface=self.listen_addr)
3
Example 16
Project: PySnip Source File: ssh.py
def create_remote_factory(namespace, users):
realm = manhole_ssh.TerminalRealm()
def create_remote_protocol(_):
return manhole.Manhole(namespace)
realm.chainedProtocolFactory.protocolFactory = create_remote_protocol
p = portal.Portal(realm)
p.registerChecker(
checkers.InMemoryUsernamePasswordDatabaseDontUse(**users))
f = manhole_ssh.ConchFactory(p)
return f
3
Example 17
Project: mythbox Source File: tap.py
def makeService(config):
t = factory.OpenSSHFactory()
t.portal = portal.Portal(unix.UnixSSHRealm())
t.portal.registerChecker(checkers.UNIXPasswordDatabase())
t.portal.registerChecker(checkers.SSHPublicKeyDatabase())
if pamauth is not None:
from twisted.cred.checkers import PluggableAuthenticationModulesChecker
t.portal.registerChecker(PluggableAuthenticationModulesChecker())
t.dataRoot = config['data']
t.moduliRoot = config['moduli'] or config['data']
port = config['port']
if config['interface']:
# Add warning here
port += ':interface='+config['interface']
return strports.service(port, t)
3
Example 18
def makeService(config):
f = ftp.FTPFactory()
r = ftp.FTPRealm(config['root'])
p = portal.Portal(r, config.get('credCheckers', []))
f.tld = config['root']
f.userAnonymous = config['userAnonymous']
f.portal = p
f.protocol = ftp.FTP
try:
portno = int(config['port'])
except KeyError:
portno = 2121
return internet.TCPServer(portno, f)
3
Example 19
Project: vumi-go Source File: auth.py
def getChild(self, conversation_key, request):
if conversation_key:
res = self.resource_class(self.worker, conversation_key)
checker = ConversationAccessChecker(self.worker, conversation_key)
realm = ConversationRealm(res)
p = portal.Portal(realm, [checker])
factory = BasicCredentialFactory("Conversation Realm")
protected_resource = HTTPAuthSessionWrapper(p, [factory])
return protected_resource
else:
return resource.NoResource()
3
Example 20
def __init__(self, settings):
self.settings = settings
self.portal = Portal(OpenRukoRealm(settings))
self.portal.registerChecker(OpenRukoCredentialChecker(settings))
self.privateKeys = {
'ssh-rsa': Key.fromFile(settings['gitmouth_private_key']),
}
self.publicKeys = {
'ssh-rsa': Key.fromFile(settings['gitmouth_public_key']),
}
3
Example 21
Project: mythbox Source File: manhole.py
def makeService(config):
port, user, password = config['port'], config['user'], config['password']
p = portal.Portal(
service.Realm(service.Service(config["tracebacks"], config.get('namespace'))),
[checkers.InMemoryUsernamePasswordDatabaseDontUse(**{user: password})]
)
return strports.service(port, pb.PBServerFactory(p, config["tracebacks"]))
3
Example 22
Project: mythbox Source File: test_newcred.py
def setUp(self):
r = self.realm = TestRealm()
p = self.portal = portal.Portal(r)
up = self.checker = checkers.InMemoryUsernamePasswordDatabaseDontUse()
up.addUser("bob", "hello")
p.registerChecker(up)
3
Example 23
Project: idavoll Source File: tap_http.py
def getManholeFactory(namespace, **passwords):
def getManHole(_):
return manhole.Manhole(namespace)
realm = manhole_ssh.TerminalRealm()
realm.chainedProtocolFactory.protocolFactory = getManHole
p = portal.Portal(realm)
p.registerChecker(
checkers.InMemoryUsernamePasswordDatabaseDontUse(**passwords))
f = manhole_ssh.ConchFactory(p)
return f
3
Example 24
def addPortal(self):
r = TestRealm()
p = cred.portal.Portal(r)
c = cred.checkers.InMemoryUsernamePasswordDatabaseDontUse()
c.addUser('[email protected]', 'passXword')
p.registerChecker(c)
self.proxy.portal = p
3
Example 25
Project: graphite Source File: manhole.py
def createManholeListener():
sshRealm = TerminalRealm()
sshRealm.chainedProtocolFactory.protocolFactory = lambda _: Manhole(namespace)
# You can uncomment this if you're lazy and want insecure authentication instead
# of setting up keys.
#credChecker = checkers.InMemoryUsernamePasswordDatabaseDontUse(carbon='')
userKeys = {
settings.MANHOLE_USER : settings.MANHOLE_PUBLIC_KEY,
}
credChecker = PublicKeyChecker(userKeys)
sshPortal = portal.Portal(sshRealm)
sshPortal.registerChecker(credChecker)
sessionFactory = ConchFactory(sshPortal)
return sessionFactory
3
Example 26
Project: wader Source File: shell.py
def get_manhole_factory(namespace, **passwords):
"""
Returns a ``ConchFactory`` instance configured with given settings
:param namespace: The namespace to use
:param passwords: The passwords to use
:rtype: `twisted.conch.manhole_ssh.ConchFactory`
"""
realm = manhole_ssh.TerminalRealm()
def getManhole(_):
return manhole.Manhole(namespace)
realm.chainedProtocolFactory.protocolFactory = getManhole
p = portal.Portal(realm)
checker = checkers.InMemoryUsernamePasswordDatabaseDontUse(**passwords)
p.registerChecker(checker)
return manhole_ssh.ConchFactory(p)
3
Example 27
Project: mythbox Source File: test_twisted.py
def getManholeFactory(namespace, **passwords):
realm = manhole_ssh.TerminalRealm()
def getManhole(_):
return manhole.Manhole(namespace)
realm.chainedProtocolFactory.protocolFactory = getManhole
p = portal.Portal(realm)
p.registerChecker(checkers.InMemoryUsernamePasswordDatabaseDontUse(**passwords))
f = manhole_ssh.ConchFactory(p)
return f
3
Example 28
Project: urwid Source File: twisted_serve_ssh.py
def create_server_factory(urwid_mind_factory):
"""Convenience to create a server factory with a portal that uses a realm
serving a given urwid widget against checkers provided.
"""
rlm = UrwidRealm(urwid_mind_factory)
ptl = Portal(rlm, urwid_mind_factory.cred_checkers)
return ConchFactory(ptl)
3
Example 29
Project: lbry Source File: DaemonControl.py
def create_auth_session(root):
pw_path = os.path.join(settings.data_dir, ".api_keys")
initialize_api_key_file(pw_path)
checker = PasswordChecker.load_file(pw_path)
realm = HttpPasswordRealm(root)
portal_to_realm = portal.Portal(realm, [checker, ])
factory = guard.BasicCredentialFactory('Login to lbrynet api')
_lbrynet_server = guard.HTTPAuthSessionWrapper(portal_to_realm, [factory, ])
return _lbrynet_server
3
Example 30
Project: vumi-go Source File: auth.py
def __init__(self, realm, vumi_api, auth_bouncer_url=None):
checkers = [GoUserSessionAccessChecker(vumi_api.session_manager)]
factories = [BasicCredentialFactory(self.AUTHENTICATION_REALM)]
if auth_bouncer_url:
checkers.append(GoAuthBouncerAccessChecker(auth_bouncer_url))
factories.append(
GoAuthBouncerCredentialFactory(self.AUTHENTICATION_REALM))
p = portal.Portal(realm, checkers)
super(GoUserAuthSessionWrapper, self).__init__(p, factories)
3
Example 31
Project: leap_mail Source File: utils.py
def __init__(self, account, *args, **kw):
LEAPIMAPServer.__init__(self, *args, **kw)
realm = TestRealm(account)
portal = Portal(realm)
checker = TestCredentialsChecker()
self.checker = checker
self.portal = portal
portal.registerChecker(checker)
3
Example 32
Project: spinoff Source File: startnode.py
def make_manhole_server(self, port, username, password):
from twisted.application.internet import TCPServer
from twisted.cred.portal import Portal
from twisted.cred.checkers import InMemoryUsernamePasswordDatabaseDontUse
from twisted.conch.manhole import ColoredManhole
from twisted.conch.manhole_ssh import ConchFactory, TerminalRealm
from twisted.conch.insults.insults import ServerProtocol
rlm = TerminalRealm()
rlm.chainedProtocolFactory = lambda: ServerProtocol(ColoredManhole, None)
auth_checker = InMemoryUsernamePasswordDatabaseDontUse(**{username: password})
return TCPServer(port, ConchFactory(Portal(rlm, [auth_checker])))
3
Example 33
Project: ldaptor Source File: addressbook.py
def getSite(config):
form = AddressBookResource()
form.remember(config, ILDAPConfig)
realm = AddressBookRealm(form)
site = appserver.NevowSite(
guard.SessionWrapper(
portal.Portal(realm, [checkers.AllowAnonymousAccess()])))
return site
3
Example 34
Project: vumi Source File: rapidsms_relay.py
def get_protected_resource(self, resource):
checker = RapidSMSRelayAccessChecker(self.get_avatar_id)
realm = RapidSMSRelayRealm(resource)
p = portal.Portal(realm, [checker])
factory = BasicCredentialFactory("RapidSMS Relay")
protected_resource = HTTPAuthSessionWrapper(p, [factory])
return protected_resource
3
Example 35
Project: ccs-calendarserver Source File: test_httpauth.py
def setUp(self):
"""
Create a portal and add an in memory checker to it.
Then set up a protectedResource that will be wrapped in each test.
"""
self.portal = portal.Portal(TestAuthRealm())
c = checkers.InMemoryUsernamePasswordDatabaseDontUse()
c.addUser('username', 'password')
self.portal.registerChecker(c)
self.credFactory = basic.BasicCredentialFactory('test realm')
self.protectedResource = ProtectedResource()
self.protectedResource.responseText = "You shouldn't see me."
3
Example 36
Project: carbon Source File: manhole.py
def createManholeListener():
sshRealm = TerminalRealm()
sshRealm.chainedProtocolFactory.protocolFactory = lambda _: Manhole(namespace)
if settings.MANHOLE_PUBLIC_KEY == 'None':
credChecker = checkers.InMemoryUsernamePasswordDatabaseDontUse()
credChecker.addUser(settings.MANHOLE_USER, '')
else:
userKeys = {
settings.MANHOLE_USER: settings.MANHOLE_PUBLIC_KEY,
}
credChecker = PublicKeyChecker(userKeys)
sshPortal = portal.Portal(sshRealm)
sshPortal.registerChecker(credChecker)
sessionFactory = ConchFactory(sshPortal)
return sessionFactory
3
Example 37
def _makeConchFactory(self):
"""
Make a L{ConchTestServerFactory}, which allows us to start a
L{ConchTestServer} -- i.e. an actually listening conch.
"""
realm = self.realmFactory()
p = portal.Portal(realm)
p.registerChecker(ConchTestPublicKeyChecker())
factory = ConchTestServerFactory()
factory.portal = p
return factory
3
Example 38
def getService(self):
factory = HoneyPotSSHFactory(version=self.version, logger=self.logger)
factory.canaryservice = self
factory.portal = portal.Portal(HoneyPotRealm())
rsa_pubKeyString, rsa_privKeyString = getRSAKeys()
dsa_pubKeyString, dsa_privKeyString = getDSAKeys()
factory.portal.registerChecker(HoneypotPasswordChecker(logger=factory.logger))
factory.portal.registerChecker(CanaryPublicKeyChecker(logger=factory.logger))
factory.publicKeys = {'ssh-rsa': keys.Key.fromString(data=rsa_pubKeyString),
'ssh-dss': keys.Key.fromString(data=dsa_pubKeyString)}
factory.privateKeys = {'ssh-rsa': keys.Key.fromString(data=rsa_privKeyString),
'ssh-dss': keys.Key.fromString(data=dsa_privKeyString)}
return internet.TCPServer(self.port, factory, interface=self.listen_addr)
3
Example 39
def addDomain(self, name, domain):
portal = cred.portal.Portal(domain)
map(portal.registerChecker, domain.getCredentialsCheckers())
self.domains[name] = domain
self.portals[name] = portal
if self.aliases and IAliasableDomain.providedBy(domain):
domain.setAliasGroup(self.aliases)
3
Example 40
def startServer(self):
realm = FileTransferTestRealm(self.testDir)
p = portal.Portal(realm)
p.registerChecker(test_ssh.ConchTestPublicKeyChecker())
fac = test_ssh.ConchTestServerFactory()
fac.portal = p
self.server = reactor.listenTCP(0, fac, interface="127.0.0.1")
3
Example 41
Project: SubliminalCollaborator Source File: test_irc_service.py
def setUp(self):
"""
Sets up a Realm, Portal, Factory, IRCUser, Transport, and Connection
for our tests.
"""
self.wordsRealm = InMemoryWordsRealm("example.com")
self.portal = portal.Portal(self.wordsRealm,
[checkers.InMemoryUsernamePasswordDatabaseDontUse(john="pass")])
self.factory = IRCFactory(self.wordsRealm, self.portal)
self.ircUser = self.factory.buildProtocol(None)
self.stringTransport = proto_helpers.StringTransport()
self.ircUser.makeConnection(self.stringTransport)
3
Example 42
Project: flumotion Source File: manhole.py
def openSSHManhole(authorizedKeysFile, namespace, portNum=-1):
from twisted.conch import manhole_ssh
def makeProtocol():
return insults.ServerProtocol(manhole.Manhole, namespace)
checker = SSHPublicKeyChecker(authorizedKeysFile)
sshRealm = manhole_ssh.TerminalRealm()
sshRealm.chainedProtocolFactory = makeProtocol
sshPortal = portal.Portal(sshRealm, [checker])
sshFactory = manhole_ssh.ConchFactory(sshPortal)
port = reactor.listenTCP(portNum, sshFactory, interface='localhost')
return port
3
Example 43
Project: SubliminalCollaborator Source File: test_service.py
def setUp(self):
self.realm = service.InMemoryWordsRealm("realmname")
self.checker = checkers.InMemoryUsernamePasswordDatabaseDontUse()
self.portal = portal.Portal(
self.realm, [self.checker])
self.serverFactory = pb.PBServerFactory(self.portal)
self.serverFactory.protocol = self._protocolFactory
self.serverFactory.unsafeTracebacks = True
self.clientFactory = pb.PBClientFactory()
self.clientFactory.unsafeTracebacks = True
self.serverPort = reactor.listenTCP(0, self.serverFactory)
self.clientConn = reactor.connectTCP(
'127.0.0.1',
self.serverPort.getHost().port,
self.clientFactory)
3
Example 44
Project: mythbox Source File: test_userauth.py
def setUp(self):
self.realm = Realm()
self.portal = Portal(self.realm)
self.portal.registerChecker(PasswordChecker())
self.portal.registerChecker(PrivateKeyChecker())
self.portal.registerChecker(PAMChecker())
self.authServer = userauth.SSHUserAuthServer()
self.authServer.transport = FakeTransport(self.portal)
self.authServer.serviceStarted()
self.authServer.supportedAuthentications.sort() # give a consistent
3
Example 45
Project: pixelated-user-agent Source File: application.py
def set_up_protected_resources(root_resource, provider, services_factory, banner=None, authenticator=None):
session_checker = SessionChecker(services_factory)
realm = PixelatedRealm()
_portal = portal.Portal(realm, [session_checker, AllowAnonymousAccess()])
anonymous_resource = LoginResource(services_factory, provider, disclaimer_banner=banner, authenticator=authenticator)
protected_resource = PixelatedAuthSessionWrapper(_portal, root_resource, anonymous_resource, [])
root_resource.initialize(provider, disclaimer_banner=banner, authenticator=authenticator)
return protected_resource
3
Example 46
Project: vumi Source File: httprpc.py
def get_authenticated_resource(self, resource):
if not self.web_username:
return resource
realm = HttpRpcRealm(resource)
checkers = [
StaticAuthChecker(self.web_username, self.web_password),
]
portal = Portal(realm, checkers)
cred_factories = [
BasicCredentialFactory(self.web_auth_domain),
]
return HTTPAuthSessionWrapper(portal, cred_factories)
3
Example 47
Project: vertex Source File: q2qstandalone.py
def setup_Q2Q(self, path,
q2qPortnum=q2q.port,
inboundTCPPortnum=q2q.port+1,
publicIP=None
):
"""Set up a Q2Q service.
"""
store = DirectoryCertificateAndUserStore(path)
# store.addPrivateCertificate("kazekage")
# store.addUser("kazekage", "username", "password1234")
self.attach(q2q.Q2QService(
protocolFactoryFactory=IdentityAdminFactory(store).examineRequest,
certificateStorage=store,
portal=Portal(store, checkers=[store]),
q2qPortnum=q2qPortnum,
inboundTCPPortnum=inboundTCPPortnum,
publicIP=publicIP,
))
3
Example 48
Project: mythbox Source File: test_twisted.py
def getTelnetFactory():
namespace = globals()
checker = checkers.InMemoryUsernamePasswordDatabaseDontUse(admin='aaa')
telnetRealm = _StupidRealm(telnet.TelnetBootstrapProtocol,
insults.ServerProtocol,
manhole.ColoredManhole,
namespace)
telnetPortal = portal.Portal(telnetRealm, [checker])
telnetFactory = protocol.ServerFactory()
telnetFactory.protocol = makeTelnetProtocol(telnetPortal)
return telnetFactory
0
Example 49
Project: tahoe-lafs Source File: ftpd.py
def __init__(self, client, accountfile, accounturl, ftp_portstr):
precondition(isinstance(accountfile, (unicode, NoneType)), accountfile)
service.MultiService.__init__(self)
r = Dispatcher(client)
p = portal.Portal(r)
if accountfile:
c = AccountFileChecker(self, accountfile)
p.registerChecker(c)
if accounturl:
c = AccountURLChecker(self, accounturl)
p.registerChecker(c)
if not accountfile and not accounturl:
# we could leave this anonymous, with just the /uri/CAP form
raise NeedRootcapLookupScheme("must provide some translation")
f = ftp.FTPFactory(p)
s = strports.service(ftp_portstr, f)
s.setServiceParent(self)
0
Example 50
Project: scrapy Source File: test_downloader_handlers.py
def setUp(self):
from twisted.protocols.ftp import FTPRealm, FTPFactory
from scrapy.core.downloader.handlers.ftp import FTPDownloadHandler
# setup dirs and test file
self.directory = self.mktemp()
os.mkdir(self.directory)
userdir = os.path.join(self.directory, self.username)
os.mkdir(userdir)
fp = FilePath(userdir)
fp.child('file.txt').setContent("I have the power!")
fp.child('file with spaces.txt').setContent("Moooooooooo power!")
# setup server
realm = FTPRealm(anonymousRoot=self.directory, userHome=self.directory)
p = portal.Portal(realm)
users_checker = checkers.InMemoryUsernamePasswordDatabaseDontUse()
users_checker.addUser(self.username, self.password)
p.registerChecker(users_checker, credentials.IUsernamePassword)
self.factory = FTPFactory(portal=p)
self.port = reactor.listenTCP(0, self.factory, interface="127.0.0.1")
self.portNum = self.port.getHost().port
self.download_handler = FTPDownloadHandler(Settings())
self.addCleanup(self.port.stopListening)