文档章节

twisted的cred

疯狂的小企鹅
 疯狂的小企鹅
发布于 2014/08/26 14:15
字数 1243
阅读 95
收藏 1

最近在看《Twisted Network Programming Essentials 2nd》一书,网上找不到中文版的(好像第一版被翻译了部分,第二版好像没被翻译),哭瞎。里面有讲cred的。

各个重要的参数说明一下:http://twistedmatrix.com/documents/13.1.0/core/howto/cred.html#auto2这里有很详细说明哦。

Credentials:与验证用户的信息有关。最常用的就是记录着用户名和密码。(我喜欢把它叫做一个装有你的用户名密码的容器。)实现了twisted.cred.credentials.ICredentials

Avatar:你验证成功后的代表着用户的一个对象。

AvatarID:这个用来表明用户的身份的。在本例子里,就是user

Credentials checker:这个是用验证你的Credentials是否合法。如果合法的话,会返回一个avatarID。例子中的InMemoryUsernamePasswordDatabaseDontUse()这是一个CredentialsChecker

Realm:为所有用户定义一些操作。在Realm的requestAvatar方法中,会传入一个avatarId,可以根据不同的用户来规定不同的权限。它会返回一个avatar对象

Portal:把一系列的CredentialsChecker集中起来。主要完成的就是把Credentials与Credentials checker间的信息进行核对。portal的login方法,会返回一个Deferred,注册回调checker的requestAvatarId,这会返回一个AvatarID,然后再注册回调一个Realm的requestAvatar。

 

下面代码,实现了一个需要用户凭证的echo服务器,使用user pass 来验证身份。

 

#!/usr/bin/env python
#coding:utf8
# Author          : tuxpy
# Email           : q8886888@qq.com
# Last modified   : 2014-08-25 15:35:35
# Filename        : tw_cred.py
# Description     : 
from zope.interface import implements,Interface
from twisted.cred import checkers,credentials,portal
from twisted.internet import protocol,reactor
 
from twisted.protocols import basic
 
class IProtocolAvatar(Interface):
    def logout():
        """
        clean up per-login resources ollocated to this avator.
        """
 
class EchoAvatar(object):
    implements(IProtocolAvatar)
 
    def logout(self):
        pass
 
class Echo(basic.LineReceiver):
    protal=None
    avatar=None
    logout=None
    delimiter='\n'
 
    def cocnnectionLost(self,reason):
        if self.logout:
            self.logout()
            self.avater=None
            seslf.logout=None
 
    def lineReceived(self,line):
        if not self.avatar:
            username,password=line.strip().split(" ")
            self.tryLogin(username,password)
        else:
            self.sendLine(line)
 
    def tryLogin(self,username,password):
        self.portal.login(credentials.UsernamePassword(username,
            password),
            None,IProtocolAvatar).addCallbacks(self._cbLogin,
                    self._ebLogin)
 
    def _cbLogin(self,(interface,avatar,logout)):
        self.avatar=avatar
        self.logout=logout
        self.sendLine("Login successful,please procees.")
 
    def _ebLogin(self,failure):
        self.sendLine("Login denied,goodbye.")
        self.transport.loseConnection()
 
class EchoFactory(protocol.Factory):
    def __init__(self,portal):
        self.portal=portal
 
    def buildProtocol(self,addr):
        protocol=Echo()
        protocol.portal=self.portal
        return protocol
        
 
class Realm(object):
    implements(portal.IRealm)
    
    def requestAvatar(self,avatarId,mind,*interfaces):
        for iface in interfaces:
            if iface is IProtocolAvatar:
                avatar=EchoAvatar()
                return IProtocolAvatar,avatar,avatar.logout
 
        raise NotImplementedError("This realm only supports the IProtocolAvatar interface.")
 
realm=Realm()
myPortal=portal.Portal(realm)
checker=checkers.InMemoryUsernamePasswordDatabaseDontUse()
checker.addUser("user","pass")
myPortal.registerChecker(checker)
reactor.listenTCP(1234,EchoFactory(myPortal))
reactor.run()


 

下面这图,很说明问题,看懂了,就基本上明白这几个

点击查看原图

 

1.先是调用portal.login方法,将Credentials(UsernamePassword),mind(通常是None),interfaces(IProtocolAvatar) 当作为参数传入。

2.把Credentials与portal中已经注册了的checker(Credentials Checkers,使用portal的rergisterChecker(checker)注册)进行信息的匹配。

3.匹配无误,就会返回一个avatarId.

4.avatarId返回,激活回调函数self.realm.requestAvatar。

5.返回符合条件的avatar

6.返回avatar和logout方法

 

这还有一张twisted how to 上的图:

点击查看原图


一些源码:

class Portal:

    """

    A mediator between clients and a realm.

 

    A portal is associated with one Realm and zero or more credentials checkers.

    When a login is attempted, the portal finds the appropriate credentials

    checker for the credentials given, invokes it, and if the credentials are

    valid, retrieves the appropriate avatar from the Realm.

 

    This class is not intended to be subclassed.  Customization should be done

    in the realm object and in the credentials checker objects.

    """

    def __init__(self, realm, checkers=()):

        """

        Create a Portal to a L{IRealm}.

        """

        self.realm = realm

        self.checkers = {}

        for checker in checkers:

            self.registerChecker(checker)

 

    def listCredentialsInterfaces(self):

        """

        Return list of credentials interfaces that can be used to login.

        """

        return self.checkers.keys()

 

    def registerChecker(self, checker, *credentialInterfaces):

        if not credentialInterfaces:

            credentialInterfaces = checker.credentialInterfaces

        for credentialInterface in credentialInterfaces:

            self.checkers[credentialInterface] = checker

 

    def login(self, credentials, mind, *interfaces):

        """

        @param credentials: an implementor of

            L{twisted.cred.credentials.ICredentials}

 

        @param mind: an object which implements a client-side interface for

            your particular realm.  In many cases, this may be None, so if the

            word 'mind' confuses you, just ignore it.

 

        @param interfaces: list of interfaces for the perspective that the mind

            wishes to attach to. Usually, this will be only one interface, for

            example IMailAccount. For highly dynamic protocols, however, this

            may be a list like (IMailAccount, IUserChooser, IServiceInfo).  To

            expand: if we are speaking to the system over IMAP, any information

            that will be relayed to the user MUST be returned as an

            IMailAccount implementor; IMAP clients would not be able to

            understand anything else. Any information about unusual status

            would have to be relayed as a single mail message in an

            otherwise-empty mailbox. However, in a web-based mail system, or a

            PB-based client, the ``mind'' object inside the web server

            (implemented with a dynamic page-viewing mechanism such as a

            Twisted Web Resource) or on the user's client program may be

            intelligent enough to respond to several ``server''-side

            interfaces.

 

        @return : A deferred which will fire a tuple of (interface,

            avatarAspect, logout).  The interface will be one of the interfaces

            passed in the 'interfaces' argument.  The 'avatarAspect' will

            implement that interface. The 'logout' object is a callable which

            will detach the mind from the avatar. It must be called when the

            user has conceptually disconnected from the service. Although in

            some cases this will not be in connectionLost (such as in a

            web-based session), it will always be at the end of a user's

            interactive session.

        """

        for i in self.checkers:

            if i.providedBy(credentials):

                return maybeDeferred(self.checkers[i].requestAvatarId, credentials

                    ).addCallback(self.realm.requestAvatar, mind, *interfaces

                    )

        ifac = providedBy(credentials)

        return defer.fail(failure.Failure(error.UnhandledCredentials(

            "No checker for %s" % ', '.join(map(reflect.qual, ifac)))))





class InMemoryUsernamePasswordDatabaseDontUse:

    """

    An extremely simple credentials checker.


    This is only of use in one-off test programs or examples which don't

    want to focus too much on how credentials are verified.


    You really don't want to use this for anything else.  It is, at best, a

    toy.  If you need a simple credentials checker for a real application,

    see L{FilePasswordDB}.

    """


    implements(ICredentialsChecker)


    credentialInterfaces = (credentials.IUsernamePassword,

                            credentials.IUsernameHashedPassword)


    def __init__(self, **users):

        self.users = users


    def addUser(self, username, password):

        self.users[username] = password


    def _cbPasswordMatch(self, matched, username):

        if matched:

            return username

        else:

            return failure.Failure(error.UnauthorizedLogin())


    def requestAvatarId(self, credentials):

        if credentials.username in self.users:

            return defer.maybeDeferred(

                credentials.checkPassword,

                self.users[credentials.username]).addCallback(

                self._cbPasswordMatch, str(credentials.username))

        else:

            return defer.fail(error.UnauthorizedLogin())


© 著作权归作者所有

疯狂的小企鹅

疯狂的小企鹅

粉丝 13
博文 42
码字总数 20243
作品 6
杭州
程序员
私信 提问
对struct cred新理解

到现在我还没有看到cred被加入内核的mainline,可惜啊,不过我个人认为它是很不错的,其精髓就是补丁 上的那一句,就是将权力和授权分离,这句话看似有点不知所云,难道权力不就是授权吗?其...

晨曦之光
2012/04/10
449
0
将要加入linux-2.6.29内核的cred

2.6.29内核我认为最重要的就是规整了内核结构,规整了代码结构,使得内核看起来更加自然,更加清晰,正如第二代rcu做到的那样,原先内核中的很多机制在2.6.29内核中都得到了规整,可以说得到...

晨曦之光
2012/04/10
71
0
将要加入linux-2.6.29内核的cred

2.6.29内核我认为最重要的就是规整了内核结构,规整了代码结构,使得内核看起来更加自然,更加清晰,正如第二代rcu做到的那样,原先内核中的很多机制在2.6.29内核中都得到了规整,可以说得到...

晨曦之光
2012/04/10
473
0
Powershell管理系列(三十四)PowerShell操作之Send-MailMessage

-----提供ADExchangeLyncSharepointCRMSCO365等微软产品实施及外包,QQ:185426445.电话18666943750 对于管理员来说需要经常测试线上系统的服务运行状态,powershell的send-mailmessage命令是...

zhou_ping
2016/10/11
0
0
(转) Twisted :第二十二部分 结束

全部完成 呼呼! 感谢你一路支持. 在我开始时完全没有想到这个系列会这样长,会花这么多时间完成,但是创建这个系列的过程使我非常享受,也希望你喜欢它. 既然我已经完成了,我会进一步考虑将其转...

水果糖
2016/01/27
22
0

没有更多内容

加载失败,请刷新页面

加载更多

计算机网络

计算机网络体系结构 OSI 其中表示层和会话层用途如下: 表示层 :数据压缩、加密以及数据描述,这使得应用程序不必关心在各台主机中数据内部格式不同的问题。 会话层 :建立及管理会话。 五层...

一只小青蛙
今天
2
0
0.01-Win10安装linux子系统

一、安装Debian子系统 -1、控制面板设置: -1.1、打开“控制面板” —— “程序” —— “启用或关闭Windows功能” —— 勾选 “适用于Linux的Windows子系统” -2、设置: -2.1、打开“设置”...

静以修身2025
昨天
2
0
init 0-6 (启动级别:init 0,1,2,3,4,5,6)

启动级别: init 0,1,2,3,4,5,6 这是个很久的知识点了,只是自己一直都迷迷糊糊的,今天在翻出来好好理解下。。 0: 停机 1:单用户形式,只root进行维护 2:多用户,不能使用net file system...

圣洁之子
昨天
2
0
Android Camera HAL浅析

1、Camera成像原理介绍 Camera工作流程图 Camera的成像原理可以简单概括如下: 景物(SCENE)通过镜头(LENS)生成的光学图像投射到图像传感器(Sensor)表面上,然后转为电信号,经过A/D(模数转...

天王盖地虎626
昨天
2
0
聊聊Elasticsearch的ProcessProbe

序 本文主要研究一下Elasticsearch的ProcessProbe ProcessProbe elasticsearch-7.0.1/server/src/main/java/org/elasticsearch/monitor/process/ProcessProbe.java public class ProcessProb......

go4it
昨天
3
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部