Debian Codegraph @

docs/web/examples/webguard.py

raw
1 # Copyright (c) Twisted Matrix Laboratories.
2 # See LICENSE for details.
3
4 """
5 This example shows how to make simple web authentication.
6
7 To run the example:
8 $ python webguard.py
9
10 When you visit http://127.0.0.1:8889/, the page will ask for an username &
11 password. See the code in main() to get the correct username & password!
12 """
13
14 import sys
15
16 from zope.interface import implementer
17
18 from twisted.cred.checkers import InMemoryUsernamePasswordDatabaseDontUse
19 from twisted.cred.portal import IRealm, Portal
20 from twisted.internet import reactor
21 from twisted.python import log
22 from twisted.web import guard, resource, server
23
24
25 class GuardedResource(resource.Resource):
26 """
27 A resource which is protected by guard and requires authentication in order
28 to access.
29 """
30
31 def getChild(self, path, request):
32 return self
33
34 def render(self, request):
35 return b"Authorized!"
36
37
38 @implementer(IRealm)
39 class SimpleRealm:
40 """
41 A realm which gives out L{GuardedResource} instances for authenticated
42 users.
43 """
44
45 def requestAvatar(self, avatarId, mind, *interfaces):
46 if resource.IResource in interfaces:
47 return resource.IResource, GuardedResource(), lambda: None
48 raise NotImplementedError()
49
50
51 def main():
52 log.startLogging(sys.stdout)
53 checkers = [InMemoryUsernamePasswordDatabaseDontUse(joe=b"blow")]
54 wrapper = guard.HTTPAuthSessionWrapper(
55 Portal(SimpleRealm(), checkers),
56 [guard.DigestCredentialFactory("md5", b"example.com")],
57 )
58 reactor.listenTCP(8889, server.Site(resource=wrapper))
59 reactor.run()
60
61
62 if __name__ == "__main__":
63 main()