Debian Codegraph @

django_xmlrpc/decorators.py

raw symbols SCIP
1 """Offers decorators to make the use of django_xmlrpc a great deal simpler
2
3 Authors::
4 Graham Binns,
5 Reza Mohammadi
6
7 Credit must go to Brendan W. McAdams <[email protected]>, who
8 posted the original SimpleXMLRPCDispatcher to the Django wiki:
9 http://code.djangoproject.com/wiki/XML-RPC
10
11 New BSD License
12 ===============
13 Copyright (c) 2007, Graham Binns http://launchpad.net/~codedragon
14
15 All rights reserved.
16
17 Redistribution and use in source and binary forms, with or without
18 modification, are permitted provided that the following conditions are met:
19
20 * Redistributions of source code must retain the above copyright notice,
21 this list of conditions and the following disclaimer.
22 * Redistributions in binary form must reproduce the above copyright notice,
23 this list of conditions and the following disclaimer in the documentation
24 and/or other materials provided with the distribution.
25 * Neither the name of the <ORGANIZATION> nor the names of its contributors
26 may be used to endorse or promote products derived from this software
27 without specific prior written permission.
28
29 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
30 "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
31 LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
32 A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
33 CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
34 EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
35 PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
36 PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
37 LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
38 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
39 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40 """
41 try:
42 from xmlrpc.client import Fault
43 except ImportError: # Python 2
44 from xmlrpclib import Fault
45 from django.contrib.auth import authenticate
46 from django.utils.translation import gettext as _
47
48
49 # Some constants for your pleasure
50 # XXX: Any standardization?
51 AUTHENTICATION_FAILED_CODE = 81
52 PERMISSION_DENIED_CODE = 82
53
54
55 class AuthenticationFailedException(Fault):
56 """An XML-RPC fault to be raised when a permission_required authentication
57 check fails
58
59 Author
60 """
61 def __init__(self):
62 Fault.__init__(self, AUTHENTICATION_FAILED_CODE,
63 _('Username and/or password is incorrect'))
64
65
66 class PermissionDeniedException(Fault):
67 """An XML-RPC fault to be raised when a permission_required permission
68 check fails
69 """
70 def __init__(self):
71 Fault.__init__(self, PERMISSION_DENIED_CODE, _('Permission denied'))
72
73
74 def xmlrpc_method(returns='string', args=None, name=None):
75 """Adds a signature to an XML-RPC function.
76
77 returns
78 The return type of the function. This can either be a string
79 description (e.g. 'string') or a type (e.g. str, bool) etc.
80
81 args
82 A list of the types of the arguments that the function accepts. These
83 can be strings or types or a mixture of the two e.g.
84 [str, bool, 'string']
85 """
86 # Args should be a list
87 if args is None:
88 args = []
89
90 def _xmlrpc_func(func):
91 """Inner function for XML-RPC method decoration. Adds a signature to
92 the method passed to it.
93
94 func
95 The function to add the signature to
96 """
97 # Add a signature to the function
98 func._xmlrpc_signature = {
99 'returns': returns,
100 'args': args
101 }
102 return func
103
104 return _xmlrpc_func
105
106 xmlrpc_func = xmlrpc_method
107
108
109 # Don't use this decorator when your service is going to be
110 # available in an unencrpted/untrusted network.
111 # Configure HTTPS transport for your web server.
112 def permission_required(perm=None):
113 """Decorator for authentication. Uses Django's built in authentication
114 framework to provide authenticated-only and permission-related access
115 to XML-RPC methods
116
117 perm
118 The permission (as a string) that the user must hold to be able to
119 call the function that is decorated with permission_required.
120 """
121 def _dec(func):
122 """An inner decorator. Adds the lookup code for the permission passed
123 in the outer method to the function passed to it.
124
125 func
126 The function to add the permission check to
127 """
128 def __authenticated_call(username, password, *args):
129 """Inner inner decorator. Adds username and password parameters to
130 a given XML-RPC function for authentication and permission
131 checking purposes and modifies the method signature appropriately
132
133 username
134 The username used for authentication
135
136 password
137 The password used for authentication
138 """
139 try:
140 user = authenticate(username=username, password=password)
141 if not user:
142 raise AuthenticationFailedException
143 if perm and not user.has_perm(perm):
144 raise PermissionDeniedException
145 except AuthenticationFailedException:
146 raise
147 except PermissionDeniedException:
148 raise
149 except:
150 raise AuthenticationFailedException
151 return func(user, *args)
152
153 # Update the function's XML-RPC signature, if the method has one
154 if hasattr(func, '_xmlrpc_signature'):
155 sig = func._xmlrpc_signature
156
157 # We just stick two string args on the front of sign['args'] to
158 # represent username and password
159 sig['args'] = (['string'] * 2) + sig['args']
160 __authenticated_call._xmlrpc_signature = sig
161
162 # Update the function's docstring
163 if func.__doc__:
164 __authenticated_call.__doc__ = func.__doc__ + \
165 "\nNote: Authentication is required."""
166 if perm:
167 __authenticated_call.__doc__ += (' this function requires '
168 '"%s" permission.' % perm)
169
170 return __authenticated_call
171
172 return _dec