3 # Copyright (c) Twisted Matrix Laboratories.
4 # See LICENSE for details.
7 Implement the realm for and run on port 8800 a PB service which allows both
8 anonymous and username/password based access.
10 Successful username/password-based login requests given an instance of
11 MyPerspective with a name which matches the username with which they
12 authenticated. Success anonymous login requests are given an instance of
13 MyPerspective with the name "Anonymous".
16 from sys import stdout
18 from zope.interface import implements
20 from twisted.python.log import startLogging
21 from twisted.cred.checkers import ANONYMOUS, AllowAnonymousAccess
22 from twisted.cred.checkers import InMemoryUsernamePasswordDatabaseDontUse
23 from twisted.cred.portal import IRealm, Portal
24 from twisted.internet import reactor
25 from twisted.spread.pb import Avatar, IPerspective, PBServerFactory
28 class MyPerspective(Avatar):
30 Trivial avatar exposing a single remote method for demonstrative
31 purposes. All successful login attempts in this example will result in
32 an avatar which is an instance of this class.
35 @ivar name: The username which was used during login or C{"Anonymous"}
36 if the login was anonymous (a real service might want to avoid the
37 collision this introduces between anonoymous users and authenticated
38 users named "Anonymous").
40 def __init__(self, name):
44 def perspective_foo(self, arg):
46 Print a simple message which gives the argument this method was
47 called with and this avatar's name.
49 print "I am %s. perspective_foo(%s) called on %s." % (
54 class MyRealm(object):
56 Trivial realm which supports anonymous and named users by creating
57 avatars which are instances of MyPerspective for either.
61 def requestAvatar(self, avatarId, mind, *interfaces):
62 if IPerspective not in interfaces:
63 raise NotImplementedError("MyRealm only handles IPerspective")
64 if avatarId is ANONYMOUS:
65 avatarId = "Anonymous"
66 return IPerspective, MyPerspective(avatarId), lambda: None
72 Create a PB server using MyRealm and run it on port 8800.
78 # Here the username/password checker is registered.
79 c1 = InMemoryUsernamePasswordDatabaseDontUse(user1="pass1", user2="pass2")
82 # Here the anonymous checker is registered.
83 c2 = AllowAnonymousAccess()
86 reactor.listenTCP(8800, PBServerFactory(p))
90 if __name__ == '__main__':