from twisted.protocols.basic import LineReceiver
from twisted.internet import reactor
from twisted.internet.protocol import ServerFactory
from twisted.cred import checkers,credentials,portal
from zope.interface import Interface,implements
class IEchoAvatarInterface(Interface):
def logout(self):
'''
Interface to credentials
'''
class EchoAvatar(object):
implements(IEchoAvatarInterface)
def logout(self):
print 'User logout!!!!'
#ERROR 06
#inherit from portal.IRealm
#you should inherit from object
class EchoRealm(object):
implements(portal.IRealm)
def requestAvatar(self,avatarId, mind, *interfaces):
if IEchoAvatarInterface in interfaces:
print 'requestAvatar is called, avatarId = ',avatarId
avatar = EchoAvatar()
return IEchoAvatarInterface, avatar, avatar.logout
raise NotImplementedError('''This Realm only support IEchoAvatarInterface''')
class EchoProtocol(LineReceiver):
def __init__(self):
self._avatarID = None
self.initPortal()
def initPortal(self):
#ERROR 01
#Write to this ??? portal.Portal(Echorealm)
aportal = portal.Portal(EchoRealm())
check = checkers.InMemoryUsernamePasswordDatabaseDontUse()
check.addUser('user','pass')
aportal.registerChecker(check)
self._portal = aportal
#ERROR 04
#lineReceived write ERROR
def lineReceived(self, line):
print '->line received:',line
if not self._avatarID:
avatar = line.strip().split(' ')
if len(avatar) != 2:
self.sendLine('Please input username and password,split by space')
else:
#print 'user and password',avatar[0],avatar[1]
self.login(avatar[0], avatar[1])
else:
self.sendLine(line)
def login(self, user, password):
print 'Prepare to login!!!'
d = self._portal.login(
credentials.UsernamePassword(user, password),
None,
IEchoAvatarInterface)
#ERROR 02
#Write to this ??? d.addcallback(self._cbLoginSuccess,self._cbLoginFail)
d.addCallbacks(self._cbLoginSuccess, self._cbLoginFail)
#ERROR 03
#Forget to add self object
def _cbLoginSuccess(self,(interface, avatar, logout)):
self._avatarID = avatar
self.sendLine('Login success!')
def _cbLoginFail(self, fail):
self.sendLine('Login failed!')
self.transport.loseConnection()
class EchoFactory(ServerFactory):
protocol = EchoProtocol
f = EchoFactory()
reactor.listenTCP(8000, f)
reactor.run()
twisted14 Echo认证演示
最新推荐文章于 2021-03-26 13:00:45 发布