twisted14 Echo认证演示

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()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值