Here are the examples of the python api twisted.cred.checkers.AllowAnonymousAccess taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
18 Examples
3
Source : cred_anonymous.py
with MIT License
from autofelix
with MIT License
from autofelix
def generateChecker(self, argstring=''):
return AllowAnonymousAccess()
theAnonymousCheckerFactory = AnonymousCheckerFactory()
3
Source : ftp.py
with MIT License
from autofelix
with MIT License
from autofelix
def __init__(self, *a, **kw):
usage.Options.__init__(self, *a, **kw)
self.addChecker(checkers.AllowAnonymousAccess())
def opt_password_file(self, filename):
0
Source : test_smtp.py
with MIT License
from autofelix
with MIT License
from autofelix
def test_acceptSenderAddress(self):
"""
Test that a C{MAIL FROM} command with an acceptable address is
responded to with the correct success code.
"""
class AcceptanceDelivery(NotImplementedDelivery):
"""
Delivery object which accepts all senders as valid.
"""
def validateFrom(self, helo, origin):
return origin
realm = SingletonRealm(smtp.IMessageDelivery, AcceptanceDelivery())
portal = Portal(realm, [AllowAnonymousAccess()])
proto = smtp.SMTP()
proto.portal = portal
trans = StringTransport()
proto.makeConnection(trans)
# Deal with the necessary preliminaries
proto.dataReceived(b'HELO example.com\r\n')
trans.clear()
# Try to specify our sender address
proto.dataReceived(b'MAIL FROM: < [email protected]>\r\n')
# Clean up the protocol before doing anything that might raise an
# exception.
proto.connectionLost(error.ConnectionLost())
# Make sure that we received exactly the correct response
self.assertEqual(
trans.value(),
b'250 Sender address accepted\r\n')
def test_deliveryRejectedSenderAddress(self):
0
Source : test_smtp.py
with MIT License
from autofelix
with MIT License
from autofelix
def test_deliveryRejectedSenderAddress(self):
"""
Test that a C{MAIL FROM} command with an address rejected by a
L{smtp.IMessageDelivery} instance is responded to with the correct
error code.
"""
class RejectionDelivery(NotImplementedDelivery):
"""
Delivery object which rejects all senders as invalid.
"""
def validateFrom(self, helo, origin):
raise smtp.SMTPBadSender(origin)
realm = SingletonRealm(smtp.IMessageDelivery, RejectionDelivery())
portal = Portal(realm, [AllowAnonymousAccess()])
proto = smtp.SMTP()
proto.portal = portal
trans = StringTransport()
proto.makeConnection(trans)
# Deal with the necessary preliminaries
proto.dataReceived(b'HELO example.com\r\n')
trans.clear()
# Try to specify our sender address
proto.dataReceived(b'MAIL FROM: < [email protected]>\r\n')
# Clean up the protocol before doing anything that might raise an
# exception.
proto.connectionLost(error.ConnectionLost())
# Make sure that we received exactly the correct response
self.assertEqual(
trans.value(),
b'550 Cannot receive from specified address '
b' < [email protected]>: Sender not acceptable\r\n')
@implementer(ICredentialsChecker)
0
Source : test_pb.py
with MIT License
from autofelix
with MIT License
from autofelix
def test_anonymousLogin(self):
"""
Verify that a PB server using a portal configured with a checker which
allows IAnonymous credentials can be logged into using IAnonymous
credentials.
"""
self.portal.registerChecker(checkers.AllowAnonymousAccess())
d = self.clientFactory.login(credentials.Anonymous(), "BRAINS!")
def cbLoggedIn(perspective):
return perspective.callRemote('echo', 123)
d.addCallback(cbLoggedIn)
d.addCallback(self.assertEqual, 123)
self.establishClientAndServer()
self.pump.flush()
return d
def test_anonymousLoginNotPermitted(self):
0
Source : test_pb.py
with MIT License
from autofelix
with MIT License
from autofelix
def test_anonymousLoginWithMultipleCheckers(self):
"""
Like L{test_anonymousLogin} but against a portal with a checker for
both IAnonymous and IUsernamePassword.
"""
self.portal.registerChecker(checkers.AllowAnonymousAccess())
self.portal.registerChecker(
checkers.InMemoryUsernamePasswordDatabaseDontUse(user=b'pass'))
d = self.clientFactory.login(credentials.Anonymous(), "BRAINS!")
def cbLogin(perspective):
return perspective.callRemote('echo', 123)
d.addCallback(cbLogin)
d.addCallback(self.assertEqual, 123)
self.establishClientAndServer()
self.pump.flush()
return d
def test_authenticatedLoginWithMultipleCheckers(self):
0
Source : test_pb.py
with MIT License
from autofelix
with MIT License
from autofelix
def test_authenticatedLoginWithMultipleCheckers(self):
"""
Like L{test_anonymousLoginWithMultipleCheckers} but check that
username/password authentication works.
"""
self.portal.registerChecker(checkers.AllowAnonymousAccess())
self.portal.registerChecker(
checkers.InMemoryUsernamePasswordDatabaseDontUse(user=b'pass'))
d = self.clientFactory.login(
credentials.UsernamePassword(b'user', b'pass'), "BRAINS!")
def cbLogin(perspective):
return perspective.callRemote('add', 100, 23)
d.addCallback(cbLogin)
d.addCallback(self.assertEqual, 123)
self.establishClientAndServer()
self.pump.flush()
return d
def test_view(self):
0
Source : test_ftp.py
with MIT License
from autofelix
with MIT License
from autofelix
def setUp(self):
# Keep a list of the protocols created so we can make sure they all
# disconnect before the tests end.
protocols = []
# Create a directory
self.directory = self.mktemp()
os.mkdir(self.directory)
self.dirPath = filepath.FilePath(self.directory)
# Start the server
p = portal.Portal(ftp.FTPRealm(
anonymousRoot=self.directory,
userHome=self.directory,
))
p.registerChecker(checkers.AllowAnonymousAccess(),
credentials.IAnonymous)
users_checker = checkers.InMemoryUsernamePasswordDatabaseDontUse()
self.username = "test-user"
self.password = "test-password"
users_checker.addUser(self.username, self.password)
p.registerChecker(users_checker, credentials.IUsernamePassword)
self.factory = ftp.FTPFactory(portal=p,
userAnonymous=self.userAnonymous)
self.port = port = reactor.listenTCP(
0, self.factory, interface="127.0.0.1")
self.addCleanup(port.stopListening)
# Hook the server's buildProtocol to make the protocol instance
# accessible to tests.
buildProtocol = self.factory.buildProtocol
d1 = defer.Deferred()
def _rememberProtocolInstance(addr):
# Done hooking this.
del self.factory.buildProtocol
protocol = buildProtocol(addr)
self.serverProtocol = protocol.wrappedProtocol
def cleanupServer():
if self.serverProtocol.transport is not None:
self.serverProtocol.transport.loseConnection()
self.addCleanup(cleanupServer)
d1.callback(None)
protocols.append(protocol)
return protocol
self.factory.buildProtocol = _rememberProtocolInstance
# Connect a client to it
portNum = port.getHost().port
clientCreator = protocol.ClientCreator(reactor, self.clientFactory)
d2 = clientCreator.connectTCP("127.0.0.1", portNum)
def gotClient(client):
self.client = client
self.addCleanup(self.client.transport.loseConnection)
protocols.append(self.client)
d2.addCallback(gotClient)
self.addCleanup(proto_helpers.waitUntilAllDisconnected,
reactor, protocols)
return defer.gatherResults([d1, d2])
def assertCommandResponse(self, command, expectedResponseLines,
0
Source : test_httpauth.py
with MIT License
from autofelix
with MIT License
from autofelix
def test_anonymousAccess(self):
"""
Anonymous requests are allowed if a L{Portal} has an anonymous checker
registered.
"""
unprotectedContents = b"contents of the unprotected child resource"
self.avatars[ANONYMOUS] = Resource()
self.avatars[ANONYMOUS].putChild(
self.childName, Data(unprotectedContents, 'text/plain'))
self.portal.registerChecker(AllowAnonymousAccess())
self.credentialFactories.append(BasicCredentialFactory('example.com'))
request = self.makeRequest([self.childName])
child = getChildForRequest(self.wrapper, request)
d = request.notifyFinish()
def cbFinished(ignored):
self.assertEqual(request.written, [unprotectedContents])
d.addCallback(cbFinished)
request.render(child)
return d
0
Source : tap.py
with MIT License
from fbla-competitive-events
with MIT License
from fbla-competitive-events
def postOptions(self):
"""
Check the validity of the specified set of options and
configure authentication.
@raise UsageError: When the set of options is invalid.
"""
from twisted.internet import reactor
if self['pop3s']:
if not self['certificate']:
raise usage.UsageError("Cannot specify --pop3s without "
"--certificate")
elif not os.path.exists(self['certificate']):
raise usage.UsageError("Certificate file %r does not exist."
% self['certificate'])
else:
self.addEndpoint(
'pop3', self['pop3s'], certificate=self['certificate'])
if self['esmtp'] and self['hostname'] is None:
raise usage.UsageError("--esmtp requires --hostname")
# If the --auth option was passed, this will be present -- otherwise,
# it won't be, which is also a perfectly valid state.
if 'credCheckers' in self:
for ch in self['credCheckers']:
self.service.smtpPortal.registerChecker(ch)
if not self['disable-anonymous']:
self.service.smtpPortal.registerChecker(checkers.AllowAnonymousAccess())
anything = False
for service in self._protoDefaults:
self[service] = self._getEndpoints(reactor, service)
if self[service]:
anything = True
if not anything:
raise usage.UsageError("You cannot disable all protocols")
class AliasUpdater:
0
Source : test_mail.py
with MIT License
from fbla-competitive-events
with MIT License
from fbla-competitive-events
def testLocalDelivery(self):
service = mail.mail.MailService()
service.smtpPortal.registerChecker(cred.checkers.AllowAnonymousAccess())
domain = mail.maildir.MaildirDirdbmDomain(service, 'domainDir')
domain.addUser('user', 'password')
service.addDomain('test.domain', domain)
service.portals[''] = service.portals['test.domain']
map(service.portals[''].registerChecker, domain.getCredentialsCheckers())
service.setQueue(mail.relay.DomainQueuer(service))
f = service.getSMTPFactory()
self.smtpServer = reactor.listenTCP(0, f, interface='127.0.0.1')
client = LineSendingProtocol([
'HELO meson',
'MAIL FROM: < user@hostname>',
'RCPT TO: < [email protected]>',
'DATA',
'This is the message',
'.',
'QUIT'
])
done = Deferred()
f = protocol.ClientFactory()
f.protocol = lambda: client
f.clientConnectionLost = lambda *args: done.callback(None)
reactor.connectTCP('127.0.0.1', self.smtpServer.getHost().port, f)
def finished(ign):
mbox = domain.requestAvatar('user', None, pop3.IMailbox)[1]
msg = mbox.getMessage(0).read()
self.assertNotEqual(msg.find('This is the message'), -1)
return self.smtpServer.stopListening()
done.addCallback(finished)
return done
def testRelayDelivery(self):
0
Source : test_mail.py
with MIT License
from fbla-competitive-events
with MIT License
from fbla-competitive-events
def testRelayDelivery(self):
# Here is the service we will connect to and send mail from
insServ = mail.mail.MailService()
insServ.smtpPortal.registerChecker(cred.checkers.AllowAnonymousAccess())
domain = mail.maildir.MaildirDirdbmDomain(insServ, 'insertionDomain')
insServ.addDomain('insertion.domain', domain)
os.mkdir('insertionQueue')
insServ.setQueue(mail.relaymanager.Queue('insertionQueue'))
insServ.domains.setDefaultDomain(mail.relay.DomainQueuer(insServ))
manager = mail.relaymanager.SmartHostSMTPRelayingManager(insServ.queue)
manager.fArgs += ('test.identity.hostname',)
helper = mail.relaymanager.RelayStateHelper(manager, 1)
# Yoink! Now the internet obeys OUR every whim!
manager.mxcalc = mail.relaymanager.MXCalculator(self.resolver)
# And this is our whim.
self.auth.addresses['destination.domain'] = ['127.0.0.1']
f = insServ.getSMTPFactory()
self.insServer = reactor.listenTCP(0, f, interface='127.0.0.1')
# Here is the service the previous one will connect to for final
# delivery
destServ = mail.mail.MailService()
destServ.smtpPortal.registerChecker(cred.checkers.AllowAnonymousAccess())
domain = mail.maildir.MaildirDirdbmDomain(destServ, 'destinationDomain')
domain.addUser('user', 'password')
destServ.addDomain('destination.domain', domain)
os.mkdir('destinationQueue')
destServ.setQueue(mail.relaymanager.Queue('destinationQueue'))
helper = mail.relaymanager.RelayStateHelper(manager, 1)
helper.startService()
f = destServ.getSMTPFactory()
self.destServer = reactor.listenTCP(0, f, interface='127.0.0.1')
# Update the port number the *first* relay will connect to, because we can't use
# port 25
manager.PORT = self.destServer.getHost().port
client = LineSendingProtocol([
'HELO meson',
'MAIL FROM: < user@wherever>',
'RCPT TO: < [email protected]>',
'DATA',
'This is the message',
'.',
'QUIT'
])
done = Deferred()
f = protocol.ClientFactory()
f.protocol = lambda: client
f.clientConnectionLost = lambda *args: done.callback(None)
reactor.connectTCP('127.0.0.1', self.insServer.getHost().port, f)
def finished(ign):
# First part of the delivery is done. Poke the queue manually now
# so we don't have to wait for the queue to be flushed.
delivery = manager.checkState()
def delivered(ign):
mbox = domain.requestAvatar('user', None, pop3.IMailbox)[1]
msg = mbox.getMessage(0).read()
self.assertNotEqual(msg.find('This is the message'), -1)
self.insServer.stopListening()
self.destServer.stopListening()
helper.stopService()
delivery.addCallback(delivered)
return delivery
done.addCallback(finished)
return done
aliasFile = StringIO.StringIO("""\
0
Source : test_smtp.py
with MIT License
from fbla-competitive-events
with MIT License
from fbla-competitive-events
def test_acceptSenderAddress(self):
"""
Test that a C{MAIL FROM} command with an acceptable address is
responded to with the correct success code.
"""
class AcceptanceDelivery(NotImplementedDelivery):
"""
Delivery object which accepts all senders as valid.
"""
def validateFrom(self, helo, origin):
return origin
realm = SingletonRealm(smtp.IMessageDelivery, AcceptanceDelivery())
portal = Portal(realm, [AllowAnonymousAccess()])
proto = smtp.SMTP()
proto.portal = portal
trans = StringTransport()
proto.makeConnection(trans)
# Deal with the necessary preliminaries
proto.dataReceived('HELO example.com\r\n')
trans.clear()
# Try to specify our sender address
proto.dataReceived('MAIL FROM: < [email protected]>\r\n')
# Clean up the protocol before doing anything that might raise an
# exception.
proto.connectionLost(error.ConnectionLost())
# Make sure that we received exactly the correct response
self.assertEqual(
trans.value(),
'250 Sender address accepted\r\n')
def test_deliveryRejectedSenderAddress(self):
0
Source : test_smtp.py
with MIT License
from fbla-competitive-events
with MIT License
from fbla-competitive-events
def test_deliveryRejectedSenderAddress(self):
"""
Test that a C{MAIL FROM} command with an address rejected by a
L{smtp.IMessageDelivery} instance is responded to with the correct
error code.
"""
class RejectionDelivery(NotImplementedDelivery):
"""
Delivery object which rejects all senders as invalid.
"""
def validateFrom(self, helo, origin):
raise smtp.SMTPBadSender(origin)
realm = SingletonRealm(smtp.IMessageDelivery, RejectionDelivery())
portal = Portal(realm, [AllowAnonymousAccess()])
proto = smtp.SMTP()
proto.portal = portal
trans = StringTransport()
proto.makeConnection(trans)
# Deal with the necessary preliminaries
proto.dataReceived('HELO example.com\r\n')
trans.clear()
# Try to specify our sender address
proto.dataReceived('MAIL FROM: < [email protected]>\r\n')
# Clean up the protocol before doing anything that might raise an
# exception.
proto.connectionLost(error.ConnectionLost())
# Make sure that we received exactly the correct response
self.assertEqual(
trans.value(),
'550 Cannot receive from specified address '
' < [email protected]>: Sender not acceptable\r\n')
@implementer(ICredentialsChecker)
0
Source : test_ftp.py
with MIT License
from fbla-competitive-events
with MIT License
from fbla-competitive-events
def setUp(self):
# Create a directory
self.directory = self.mktemp()
os.mkdir(self.directory)
self.dirPath = filepath.FilePath(self.directory)
# Start the server
p = portal.Portal(ftp.FTPRealm(
anonymousRoot=self.directory,
userHome=self.directory,
))
p.registerChecker(checkers.AllowAnonymousAccess(),
credentials.IAnonymous)
users_checker = checkers.InMemoryUsernamePasswordDatabaseDontUse()
self.username = "test-user"
self.password = "test-password"
users_checker.addUser(self.username, self.password)
p.registerChecker(users_checker, credentials.IUsernamePassword)
self.factory = ftp.FTPFactory(portal=p,
userAnonymous=self.userAnonymous)
port = reactor.listenTCP(0, self.factory, interface="127.0.0.1")
self.addCleanup(port.stopListening)
# Hook the server's buildProtocol to make the protocol instance
# accessible to tests.
buildProtocol = self.factory.buildProtocol
d1 = defer.Deferred()
def _rememberProtocolInstance(addr):
# Done hooking this.
del self.factory.buildProtocol
protocol = buildProtocol(addr)
self.serverProtocol = protocol.wrappedProtocol
def cleanupServer():
if self.serverProtocol.transport is not None:
self.serverProtocol.transport.loseConnection()
self.addCleanup(cleanupServer)
d1.callback(None)
return protocol
self.factory.buildProtocol = _rememberProtocolInstance
# Connect a client to it
portNum = port.getHost().port
clientCreator = protocol.ClientCreator(reactor, self.clientFactory)
d2 = clientCreator.connectTCP("127.0.0.1", portNum)
def gotClient(client):
self.client = client
self.addCleanup(self.client.transport.loseConnection)
d2.addCallback(gotClient)
return defer.gatherResults([d1, d2])
def assertCommandResponse(self, command, expectedResponseLines,
0
Source : test_pb.py
with MIT License
from fbla-competitive-events
with MIT License
from fbla-competitive-events
def test_anonymousLogin(self):
"""
Verify that a PB server using a portal configured with a checker which
allows IAnonymous credentials can be logged into using IAnonymous
credentials.
"""
self.portal.registerChecker(checkers.AllowAnonymousAccess())
factory = pb.PBClientFactory()
d = factory.login(credentials.Anonymous(), "BRAINS!")
def cbLoggedIn(perspective):
return perspective.callRemote('echo', 123)
d.addCallback(cbLoggedIn)
d.addCallback(self.assertEqual, 123)
d.addCallback(self._disconnect, factory)
connector = reactor.connectTCP("127.0.0.1", self.portno, factory)
self.addCleanup(connector.disconnect)
return d
def test_anonymousLoginNotPermitted(self):
0
Source : test_pb.py
with MIT License
from fbla-competitive-events
with MIT License
from fbla-competitive-events
def test_anonymousLoginWithMultipleCheckers(self):
"""
Like L{test_anonymousLogin} but against a portal with a checker for
both IAnonymous and IUsernamePassword.
"""
self.portal.registerChecker(checkers.AllowAnonymousAccess())
self.portal.registerChecker(
checkers.InMemoryUsernamePasswordDatabaseDontUse(user='pass'))
factory = pb.PBClientFactory()
d = factory.login(credentials.Anonymous(), "BRAINS!")
def cbLogin(perspective):
return perspective.callRemote('echo', 123)
d.addCallback(cbLogin)
d.addCallback(self.assertEqual, 123)
d.addCallback(self._disconnect, factory)
connector = reactor.connectTCP('127.0.0.1', self.portno, factory)
self.addCleanup(connector.disconnect)
return d
def test_authenticatedLoginWithMultipleCheckers(self):
0
Source : test_pb.py
with MIT License
from fbla-competitive-events
with MIT License
from fbla-competitive-events
def test_authenticatedLoginWithMultipleCheckers(self):
"""
Like L{test_anonymousLoginWithMultipleCheckers} but check that
username/password authentication works.
"""
self.portal.registerChecker(checkers.AllowAnonymousAccess())
self.portal.registerChecker(
checkers.InMemoryUsernamePasswordDatabaseDontUse(user='pass'))
factory = pb.PBClientFactory()
d = factory.login(
credentials.UsernamePassword('user', 'pass'), "BRAINS!")
def cbLogin(perspective):
return perspective.callRemote('add', 100, 23)
d.addCallback(cbLogin)
d.addCallback(self.assertEqual, 123)
d.addCallback(self._disconnect, factory)
connector = reactor.connectTCP('127.0.0.1', self.portno, factory)
self.addCleanup(connector.disconnect)
return d
def test_view(self):