OLD | NEW |
| (Empty) |
1 # Copyright (c) 2001-2004 Twisted Matrix Laboratories. | |
2 # See LICENSE for details. | |
3 | |
4 # | |
5 | |
6 """ | |
7 A simple guard framework for implementing web sites that only need | |
8 'Anonymous' vs 'Logged on' distinction, but nothing more. | |
9 | |
10 If you need | |
11 - multiple levels of access, or | |
12 - multiple-interface applications, or | |
13 - anything else more complex than 'Logged on' and 'Not logged on' | |
14 | |
15 you need to use twisted.web.woven.guard directly. | |
16 """ | |
17 | |
18 from twisted.cred import portal, checkers as checkerslib | |
19 from twisted.web import resource, util | |
20 from twisted.web.woven import guard | |
21 from zope.interface import implements | |
22 | |
23 | |
24 class Authenticated: | |
25 | |
26 def __init__(self, name=None): | |
27 self.name = name | |
28 | |
29 def __nonzero__(self): | |
30 return bool(self.name) | |
31 | |
32 | |
33 class MarkAuthenticatedResource: | |
34 | |
35 implements(resource.IResource) | |
36 | |
37 isLeaf = False | |
38 | |
39 def __init__(self, resource, name): | |
40 self.authenticated = Authenticated(name) | |
41 self.resource = resource | |
42 | |
43 def render(self, request): | |
44 request.setComponent(Authenticated, self.authenticated) | |
45 return self.resource.render(request) | |
46 | |
47 def getChildWithDefault(self, path, request): | |
48 request.setComponent(Authenticated, self.authenticated) | |
49 return self.resource.getChildWithDefault(path, request) | |
50 | |
51 | |
52 class MarkingRealm: | |
53 | |
54 implements(portal.IRealm) | |
55 | |
56 def __init__(self, resource, nonauthenticated=None): | |
57 self.resource = resource | |
58 self.nonauthenticated = (nonauthenticated or | |
59 MarkAuthenticatedResource(resource, None)) | |
60 | |
61 def requestAvatar(self, avatarId, mind, *interfaces): | |
62 if resource.IResource not in interfaces: | |
63 raise NotImplementedError("no interface") | |
64 if avatarId: | |
65 return (resource.IResource, | |
66 MarkAuthenticatedResource(self.resource, avatarId), | |
67 lambda:None) | |
68 else: | |
69 return resource.IResource, self.nonauthenticated, lambda:None | |
70 | |
71 | |
72 def parentRedirect(_): | |
73 return util.ParentRedirect() | |
74 | |
75 def guardResource(resource, checkers, callback=parentRedirect, errback=None, | |
76 nonauthenticated=None): | |
77 myPortal = portal.Portal(MarkingRealm(resource, nonauthenticated)) | |
78 for checker in checkers+[checkerslib.AllowAnonymousAccess()]: | |
79 myPortal.registerChecker(checker) | |
80 un = guard.UsernamePasswordWrapper(myPortal, | |
81 callback=callback, errback=errback) | |
82 return guard.SessionWrapper(un) | |
OLD | NEW |