~divmod-dev/divmod.org/trunk

« back to all changes in this revision

Viewing changes to Epsilon/doc/listings/amp/auth_server.py

  • Committer: Jean-Paul Calderone
  • Date: 2014-06-29 20:33:04 UTC
  • mfrom: (2749.1.1 remove-epsilon-1325289)
  • Revision ID: exarkun@twistedmatrix.com-20140629203304-gdkmbwl1suei4m97
mergeĀ lp:~exarkun/divmod.org/remove-epsilon-1325289

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (c) 2008 Divmod.  See LICENSE for details.
2
 
 
3
 
"""
4
 
An AMP server which requires authentication of its clients before exposing an
5
 
addition command.
6
 
"""
7
 
 
8
 
from sys import stdout
9
 
 
10
 
from twisted.python.log import startLogging, msg
11
 
from twisted.internet import reactor
12
 
from twisted.cred.checkers import InMemoryUsernamePasswordDatabaseDontUse
13
 
from twisted.cred.portal import Portal
14
 
from twisted.protocols.amp import IBoxReceiver, Command, Integer, AMP
15
 
 
16
 
from epsilon.ampauth import CredAMPServerFactory
17
 
 
18
 
 
19
 
class Add(Command):
20
 
    """
21
 
    An example of an application-defined command which should be made available
22
 
    to clients after they successfully authenticate.
23
 
    """
24
 
    arguments = [("left", Integer()),
25
 
                 ("right", Integer())]
26
 
 
27
 
    response = [("sum", Integer())]
28
 
 
29
 
 
30
 
 
31
 
class Adder(AMP):
32
 
    """
33
 
    An example of an application-defined AMP protocol, the responders defined
34
 
    by which should only be available to clients after they have successfully
35
 
    authenticated.
36
 
    """
37
 
    def __init__(self, avatarId):
38
 
        AMP.__init__(self)
39
 
        self.avatarId = avatarId
40
 
 
41
 
 
42
 
    @Add.responder
43
 
    def add(self, left, right):
44
 
        msg("Adding %d to %d for %s" % (left, right, self.avatarId))
45
 
        return {'sum': left + right}
46
 
 
47
 
 
48
 
 
49
 
class AdditionRealm(object):
50
 
    """
51
 
    An example of an application-defined realm.
52
 
    """
53
 
    def requestAvatar(self, avatarId, mind, *interfaces):
54
 
        """
55
 
        Create Adder avatars for any IBoxReceiver request.
56
 
        """
57
 
        if IBoxReceiver in interfaces:
58
 
            return (IBoxReceiver, Adder(avatarId), lambda: None)
59
 
        raise NotImplementedError()
60
 
 
61
 
 
62
 
 
63
 
def main():
64
 
    """
65
 
    Start the AMP server and the reactor.
66
 
    """
67
 
    startLogging(stdout)
68
 
    checker = InMemoryUsernamePasswordDatabaseDontUse()
69
 
    checker.addUser("testuser", "examplepass")
70
 
    realm = AdditionRealm()
71
 
    factory = CredAMPServerFactory(Portal(realm, [checker]))
72
 
    reactor.listenTCP(7805, factory)
73
 
    reactor.run()
74
 
 
75
 
 
76
 
if __name__ == '__main__':
77
 
    main()