Initial import to Tizen
[profile/ivi/python-twisted.git] / doc / web / examples / webguard.py
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 implements
17
18 from twisted.python import log
19 from twisted.internet import reactor
20 from twisted.web import server, resource, guard
21 from twisted.cred.portal import IRealm, Portal
22 from twisted.cred.checkers import InMemoryUsernamePasswordDatabaseDontUse
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     def getChild(self, path, request):
31         return self
32
33
34     def render(self, request):
35         return "Authorized!"
36
37
38
39 class SimpleRealm(object):
40     """
41     A realm which gives out L{GuardedResource} instances for authenticated
42     users.
43     """
44     implements(IRealm)
45
46     def requestAvatar(self, avatarId, mind, *interfaces):
47         if resource.IResource in interfaces:
48             return resource.IResource, GuardedResource(), lambda: None
49         raise NotImplementedError()
50
51
52
53 def main():
54     log.startLogging(sys.stdout)
55     checkers = [InMemoryUsernamePasswordDatabaseDontUse(joe='blow')]
56     wrapper = guard.HTTPAuthSessionWrapper(
57         Portal(SimpleRealm(), checkers),
58         [guard.DigestCredentialFactory('md5', 'example.com')])
59     reactor.listenTCP(8889, server.Site(
60           resource = wrapper))
61     reactor.run()
62
63 if __name__ == '__main__':
64     main()