aboutsummaryrefslogtreecommitdiffstats
path: root/djangorestframework/compat.py
blob: 38119811648744f76bb25827f3e3e487de16dfc7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
"""
The :mod:`compat` module provides support for backwards compatibility with older versions of django/python.
"""
import django

# cStringIO only if it's available, otherwise StringIO
try:
    import cStringIO as StringIO
except ImportError:
    import StringIO


# parse_qs from 'urlparse' module unless python 2.5, in which case from 'cgi'
try:
    # python >= 2.6
    from urlparse import parse_qs
except ImportError:
    # python < 2.6
    from cgi import parse_qs


# django.test.client.RequestFactory (Required for Django < 1.3)
try:
    from django.test.client import RequestFactory
except ImportError:
    from django.test import Client
    from django.core.handlers.wsgi import WSGIRequest

    # From: http://djangosnippets.org/snippets/963/
    # Lovely stuff
    class RequestFactory(Client):
        """
        Class that lets you create mock :obj:`Request` objects for use in testing.

        Usage::

            rf = RequestFactory()
            get_request = rf.get('/hello/')
            post_request = rf.post('/submit/', {'foo': 'bar'})

        This class re-uses the :class:`django.test.client.Client` interface. Of which
        you can find the docs here__.

        __ http://www.djangoproject.com/documentation/testing/#the-test-client

        Once you have a `request` object you can pass it to any :func:`view` function,
        just as if that :func:`view` had been hooked up using a URLconf.
        """
        def request(self, **request):
            """
            Similar to parent class, but returns the :obj:`request` object as soon as it
            has created it.
            """
            environ = {
                'HTTP_COOKIE': self.cookies,
                'PATH_INFO': '/',
                'QUERY_STRING': '',
                'REQUEST_METHOD': 'GET',
                'SCRIPT_NAME': '',
                'SERVER_NAME': 'testserver',
                'SERVER_PORT': 80,
                'SERVER_PROTOCOL': 'HTTP/1.1',
            }
            environ.update(self.defaults)
            environ.update(request)
            return WSGIRequest(environ)

# django.views.generic.View (Django >= 1.3)
try:
    from django.views.generic import View
    if not hasattr(View, 'head'):
        # First implementation of Django class-based views did not include head method
        # in base View class - https://code.djangoproject.com/ticket/15668
        class ViewPlusHead(View):
            def head(self, request, *args, **kwargs):
                return self.get(request, *args, **kwargs)
        View = ViewPlusHead

except ImportError:
    from django import http
    from django.utils.functional import update_wrapper
    # from django.utils.log import getLogger
    # from django.utils.decorators import classonlymethod

    # logger = getLogger('django.request') - We'll just drop support for logger if running Django <= 1.2
    # Might be nice to fix this up sometime to allow djangorestframework.compat.View to match 1.3's View more closely

    class View(object):
        """
        Intentionally simple parent class for all views. Only implements
        dispatch-by-method and simple sanity checking.
        """

        http_method_names = ['get', 'post', 'put', 'delete', 'head', 'options', 'trace']

        def __init__(self, **kwargs):
            """
            Constructor. Called in the URLconf; can contain helpful extra
            keyword arguments, and other things.
            """
            # Go through keyword arguments, and either save their values to our
            # instance, or raise an error.
            for key, value in kwargs.iteritems():
                setattr(self, key, value)

        # @classonlymethod - We'll just us classmethod instead if running Django <= 1.2
        @classmethod
        def as_view(cls, **initkwargs):
            """
            Main entry point for a request-response process.
            """
            # sanitize keyword arguments
            for key in initkwargs:
                if key in cls.http_method_names:
                    raise TypeError(u"You tried to pass in the %s method name as a "
                                    u"keyword argument to %s(). Don't do that."
                                    % (key, cls.__name__))
                if not hasattr(cls, key):
                    raise TypeError(u"%s() received an invalid keyword %r" % (
                        cls.__name__, key))

            def view(request, *args, **kwargs):
                self = cls(**initkwargs)
                return self.dispatch(request, *args, **kwargs)

            # take name and docstring from class
            update_wrapper(view, cls, updated=())

            # and possible attributes set by decorators
            # like csrf_exempt from dispatch
            update_wrapper(view, cls.dispatch, assigned=())
            return view

        def dispatch(self, request, *args, **kwargs):
            # Try to dispatch to the right method; if a method doesn't exist,
            # defer to the error handler. Also defer to the error handler if the
            # request method isn't on the approved list.
            if request.method.lower() in self.http_method_names:
                handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
            else:
                handler = self.http_method_not_allowed
            self.request = request
            self.args = args
            self.kwargs = kwargs
            return handler(request, *args, **kwargs)

        def http_method_not_allowed(self, request, *args, **kwargs):
            allowed_methods = [m for m in self.http_method_names if hasattr(self, m)]
            #logger.warning('Method Not Allowed (%s): %s' % (request.method, request.path),
            #    extra={
            #        'status_code': 405,
            #        'request': self.request
            #    }
            #)
            return http.HttpResponseNotAllowed(allowed_methods)

        def head(self, request, *args, **kwargs):
            return self.get(request, *args, **kwargs)

# PUT, DELETE do not require CSRF until 1.4.  They should.  Make it better.
if django.VERSION >= (1, 4):
    from django.middleware.csrf import CsrfViewMiddleware
else:
    import hashlib
    import re
    import random
    import logging
    import urlparse

    from django.conf import settings
    from django.core.urlresolvers import get_callable

    try:
        from logging import NullHandler
    except ImportError:
        class NullHandler(logging.Handler):
            def emit(self, record):
                pass

    logger = logging.getLogger('django.request')

    if not logger.handlers:
        logger.addHandler(NullHandler())

    def same_origin(url1, url2):
        """
        Checks if two URLs are 'same-origin'
        """
        p1, p2 = urlparse.urlparse(url1), urlparse.urlparse(url2)
        return p1[0:2] == p2[0:2]

    def constant_time_compare(val1, val2):
        """
        Returns True if the two strings are equal, False otherwise.

        The time taken is independent of the number of characters that match.
        """
        if len(val1) != len(val2):
            return False
        result = 0
        for x, y in zip(val1, val2):
            result |= ord(x) ^ ord(y)
        return result == 0

    # Use the system (hardware-based) random number generator if it exists.
    if hasattr(random, 'SystemRandom'):
        randrange = random.SystemRandom().randrange
    else:
        randrange = random.randrange
    _MAX_CSRF_KEY = 18446744073709551616L     # 2 << 63

    REASON_NO_REFERER = "Referer checking failed - no Referer."
    REASON_BAD_REFERER = "Referer checking failed - %s does not match %s."
    REASON_NO_CSRF_COOKIE = "CSRF cookie not set."
    REASON_BAD_TOKEN = "CSRF token missing or incorrect."


    def _get_failure_view():
        """
        Returns the view to be used for CSRF rejections
        """
        return get_callable(settings.CSRF_FAILURE_VIEW)


    def _get_new_csrf_key():
        return hashlib.md5("%s%s" % (randrange(0, _MAX_CSRF_KEY), settings.SECRET_KEY)).hexdigest()


    def get_token(request):
        """
        Returns the the CSRF token required for a POST form. The token is an
        alphanumeric value.

        A side effect of calling this function is to make the the csrf_protect
        decorator and the CsrfViewMiddleware add a CSRF cookie and a 'Vary: Cookie'
        header to the outgoing response.  For this reason, you may need to use this
        function lazily, as is done by the csrf context processor.
        """
        request.META["CSRF_COOKIE_USED"] = True
        return request.META.get("CSRF_COOKIE", None)


    def _sanitize_token(token):
        # Allow only alphanum, and ensure we return a 'str' for the sake of the post
        # processing middleware.
        token = re.sub('[^a-zA-Z0-9]', '', str(token.decode('ascii', 'ignore')))
        if token == "":
            # In case the cookie has been truncated to nothing at some point.
            return _get_new_csrf_key()
        else:
            return token

    class CsrfViewMiddleware(object):
        """
        Middleware that requires a present and correct csrfmiddlewaretoken
        for POST requests that have a CSRF cookie, and sets an outgoing
        CSRF cookie.

        This middleware should be used in conjunction with the csrf_token template
        tag.
        """
        # The _accept and _reject methods currently only exist for the sake of the
        # requires_csrf_token decorator.
        def _accept(self, request):
            # Avoid checking the request twice by adding a custom attribute to
            # request.  This will be relevant when both decorator and middleware
            # are used.
            request.csrf_processing_done = True
            return None

        def _reject(self, request, reason):
            return _get_failure_view()(request, reason=reason)

        def process_view(self, request, callback, callback_args, callback_kwargs):

            if getattr(request, 'csrf_processing_done', False):
                return None

            try:
                csrf_token = _sanitize_token(request.COOKIES[settings.CSRF_COOKIE_NAME])
                # Use same token next time
                request.META['CSRF_COOKIE'] = csrf_token
            except KeyError:
                csrf_token = None
                # Generate token and store it in the request, so it's available to the view.
                request.META["CSRF_COOKIE"] = _get_new_csrf_key()

            # Wait until request.META["CSRF_COOKIE"] has been manipulated before
            # bailing out, so that get_token still works
            if getattr(callback, 'csrf_exempt', False):
                return None

            # Assume that anything not defined as 'safe' by RC2616 needs protection.
            if request.method not in ('GET', 'HEAD', 'OPTIONS', 'TRACE'):
                if getattr(request, '_dont_enforce_csrf_checks', False):
                    # Mechanism to turn off CSRF checks for test suite.  It comes after
                    # the creation of CSRF cookies, so that everything else continues to
                    # work exactly the same (e.g. cookies are sent etc), but before the
                    # any branches that call reject()
                    return self._accept(request)

                if request.is_secure():
                    # Suppose user visits http://example.com/
                    # An active network attacker,(man-in-the-middle, MITM) sends a
                    # POST form which targets https://example.com/detonate-bomb/ and
                    # submits it via javascript.
                    #
                    # The attacker will need to provide a CSRF cookie and token, but
                    # that is no problem for a MITM and the session independent
                    # nonce we are using. So the MITM can circumvent the CSRF
                    # protection. This is true for any HTTP connection, but anyone
                    # using HTTPS expects better!  For this reason, for
                    # https://example.com/ we need additional protection that treats
                    # http://example.com/ as completely untrusted.  Under HTTPS,
                    # Barth et al. found that the Referer header is missing for
                    # same-domain requests in only about 0.2% of cases or less, so
                    # we can use strict Referer checking.
                    referer = request.META.get('HTTP_REFERER')
                    if referer is None:
                        logger.warning('Forbidden (%s): %s' % (REASON_NO_REFERER, request.path),
                            extra={
                                'status_code': 403,
                                'request': request,
                            }
                        )
                        return self._reject(request, REASON_NO_REFERER)

                    # Note that request.get_host() includes the port
                    good_referer = 'https://%s/' % request.get_host()
                    if not same_origin(referer, good_referer):
                        reason = REASON_BAD_REFERER % (referer, good_referer)
                        logger.warning('Forbidden (%s): %s' % (reason, request.path),
                            extra={
                                'status_code': 403,
                                'request': request,
                            }
                        )
                        return self._reject(request, reason)

                if csrf_token is None:
                    # No CSRF cookie. For POST requests, we insist on a CSRF cookie,
                    # and in this way we can avoid all CSRF attacks, including login
                    # CSRF.
                    logger.warning('Forbidden (%s): %s' % (REASON_NO_CSRF_COOKIE, request.path),
                        extra={
                            'status_code': 403,
                            'request': request,
                        }
                    )
                    return self._reject(request, REASON_NO_CSRF_COOKIE)

                # check non-cookie token for match
                request_csrf_token = ""
                if request.method == "POST":
                    request_csrf_token = request.POST.get('csrfmiddlewaretoken', '')

                if request_csrf_token == "":
                    # Fall back to X-CSRFToken, to make things easier for AJAX,
                    # and possible for PUT/DELETE
                    request_csrf_token = request.META.get('HTTP_X_CSRFTOKEN', '')

                if not constant_time_compare(request_csrf_token, csrf_token):
                    logger.warning('Forbidden (%s): %s' % (REASON_BAD_TOKEN, request.path),
                        extra={
                            'status_code': 403,
                            'request': request,
                        }
                    )
                    return self._reject(request, REASON_BAD_TOKEN)

            return self._accept(request)


# Markdown is optional
try:
    import markdown

    class CustomSetextHeaderProcessor(markdown.blockprocessors.BlockProcessor):
        """
        Class for markdown < 2.1

        Override `markdown`'s :class:`SetextHeaderProcessor`, so that ==== headers are <h2> and ---- heade

        We use <h1> for the resource name.
        """
        import re
        # Detect Setext-style header. Must be first 2 lines of block.
        RE = re.compile(r'^.*?\n[=-]{3,}', re.MULTILINE)

        def test(self, parent, block):
            return bool(self.RE.match(block))

        def run(self, parent, blocks):
            lines = blocks.pop(0).split('\n')
            # Determine level. ``=`` is 1 and ``-`` is 2.
            if lines[1].startswith('='):
                level = 2
            else:
                level = 3
            h = markdown.etree.SubElement(parent, 'h%d' % level)
            h.text = lines[0].strip()
            if len(lines) > 2:
                # Block contains additional lines. Add to  master blocks for later.
                blocks.insert(0, '\n'.join(lines[2:]))

    def apply_markdown(text):
        """
        Simple wrapper around :func:`markdown.markdown` to set the base level
        of '#' style headers to <h2>.
        """

        extensions = ['headerid(level=2)']
        safe_mode = False,

        if markdown.version_info < (2, 1):
            output_format = markdown.DEFAULT_OUTPUT_FORMAT

            md = markdown.Markdown(extensions=markdown.load_extensions(extensions),
                               safe_mode=safe_mode,
                               output_format=output_format)
            md.parser.blockprocessors['setextheader'] = CustomSetextHeaderProcessor(md.parser)
        else:
            md = markdown.Markdown(extensions=extensions, safe_mode=safe_mode)
        return md.convert(text)

except ImportError:
    apply_markdown = None

# Yaml is optional
try:
    import yaml
except ImportError:
    yaml = None

"s1"> </file> <file name="script.js"> function MyCtrl($scope) { $scope.action = function() { $scope.name = 'OK'; } $scope.name = 'World'; } </file> </example> <a name="model"></a> # Model <img class="pull-right" style="padding-left: 3em; padding-bottom: 1em;" src="img/guide/concepts-model.png"> The model is the data which is used merged with the template to produce the view. To be able to render the model into the view, the model has to be referenceable from the scope. Unlike many other frameworks Angular makes no restrictions or requirements an the model. There are no classes to inherit from or special accessor methods for accessing or changing the model. The model can be primitive, object hash, or a full object Type. In short the model is a plain JavaScript object. <div class="clear"> </div> <a name="view"></a> # View <img class="pull-right" style="padding-left: 3em; padding-bottom: 1em;" src="img/guide/concepts-view.png"> The view is what the users sees. The view begins its life as a template, it is merged with the model and finally rendered into the browser DOM. Angular takes a very different approach to rendering the view, to most other templating systems. * **Others** - Most templating systems begin as an HTML string with special templating markup. Often the template markup breaks the HTML syntax which means that the template can not be edited by an HTML editor. The template string is then parsed by the template engine, and merged with the data. The result of the merge is an HTML string. The HTML string is then written to the browser using the `.innerHTML`, which causes the browser to render the HTML. When the model changes the whole process needs to be repeated. The granularity of the template is the granularity of the DOM updates. The key here is that the templating system manipulates strings. * **Angular** - Angular is different, since its templating system works on DOM objects not on strings. The template is still written in HTML string, but it is HTML (not HTML with template sprinkled in.) The browser parses the HTML into DOM, and the DOM becomes the input to the template engine know as the {@link api/ng.$compile compiler}. The compiler looks for {@link guide/directive directives} which in turn set up {@link api/ng.$rootScope.Scope#$watch watches} on the model. The result is a continuously updating view which does not need template model re-merging. Your model becomes the single source-of-truth for your view. <div class="clear"> </div> <example> <file name="index.html"> <div ng-init="list = ['Chrome', 'Safari', 'Firefox', 'IE'] "> <input ng-model="list" ng-list> <br> <input ng-model="list" ng-list> <br> <pre>list={{list}}</pre> <br> <ol> <li ng-repeat="item in list"> {{item}} </li> </ol> </div> </file> </example> <a name="directives"></a> # Directives A directive is a behavior or DOM transformation which is triggered by a presence of an attribute, element name, or a class name. A directive allows you to extend the HTML vocabulary in a declarative fashion. Following is an example which enables data-binding for the `contenteditable` in HTML. <example module="directive"> <file name="script.js"> angular.module('directive', []).directive('contenteditable', function() { return { require: 'ngModel', link: function(scope, elm, attrs, ctrl) { // view -> model elm.bind('blur', function() { scope.$apply(function() { ctrl.$setViewValue(elm.html()); }); }); // model -> view ctrl.render = function(value) { elm.html(value); }; // load init value from DOM ctrl.$setViewValue(elm.html()); } }; }); </file> <file name="index.html"> <div contentEditable="true" ng-model="content">Edit Me</div> <pre>model = {{content}}</pre> </file> <file name="style.css"> div[contentEditable] { cursor: pointer; background-color: #D0D0D0; margin-bottom: 1em; padding: 1em; } </file> </example> <a name="filters"></a> # Filters {@link api/ng.$filter Filters} perform data transformation roles. Typically they are used in conjunction with the locale to format the data in locale specific output. They follow the spirit of UNIX filters and use similar syntax `|` (pipe). <example> <file name="index.html"> <div ng-init="list = ['Chrome', 'Safari', 'Firefox', 'IE'] "> Number formatting: {{ 1234567890 | number }} <br> array filtering <input ng-model="predicate"> {{ list | filter:predicate | json }} </div> </file> </example> <a name="module"></a> <a name="injector"></a> # Modules and the Injector <img class="pull-right" style="padding-left: 3em; padding-bottom: 1em;" src="img/guide/concepts-module-injector.png"> An {@link api/AUTO.$injector injector} is a service locator. There is a single {@link api/AUTO.$injector injector} per Angular {@link api/ng.directive:ngApp application}. The {@link api/AUTO.$injector injector} provides a way to look up an object instance by its name. The injector keeps an internal cache of all objects so that repeated calls to get the same object name result in the same instance. If the object does not exist, then the {@link api/AUTO.$injector injector} asks the instance factory to create a new instance. A {@link api/angular.Module module} is a way to configure the injector's instance factory, known as a {@link api/AUTO.$provide provider}. <div class='clear'></div> <pre> // Create a module var myModule = angular.module('myModule', []) // Configure the injector myModule.factory('serviceA', function() { return { // instead of {}, put your object creation here }; }); // create an injector and configure it from 'myModule' var $injector = angular.injector(['myModule']); // retrieve an object from the injector by name var serviceA = $injector.get('serviceA'); // always true because of instance cache $injector.get('serviceA') === $injector.get('serviceA'); </pre> But the real magic of the {@link api/AUTO.$injector injector} is that it can be used to {@link api/AUTO.$injector#invoke call} methods and {@link api/AUTO.$injector#instantiate instantiate} types. This subtle feature is what allows the methods and types to ask for their dependencies instead of having to look for them. <pre> // You write functions such as this one. function doSomething(serviceA, serviceB) { // do something here. } // Angular provides the injector for your application var $injector = ...; /////////////////////////////////////////////// // the old-school way of getting dependencies. var serviceA = $injector.get('serviceA'); var serviceB = $injector.get('serviceB'); // now call the function doSomething(serviceA, serviceB); /////////////////////////////////////////////// // the cool way of getting dependencies. // the $injector will supply the arguments to the function automatically $injector.invoke(doSomething); // This is how the framework calls your functions </pre> Notice that the only thing you needed to write was the function, and list the dependencies in the function arguments. When angular calls the function, it will use the {@link api/AUTO.$injector#invoke call} which will automatically fill the function arguments. Examine the `ClockCtrl` bellow, and notice how it lists the dependencies in the constructor. When the {@link api/ng.directive:ngController ng-controller} instantiates the controller it automatically provides the dependencies. There is no need to create dependencies, look for dependencies, or even get a reference to the injector. <example module="timeExampleModule"> <file name="index.html"> <div ng-controller="ClockCtrl"> Current time is: {{ time.now }} </div> </file> <file name="script.js"> angular.module('timeExampleModule', []). // Declare new object call time, // which will be available for injection factory('time', function($timeout) { var time = {}; (function tick() { time.now = new Date().toString(); $timeout(tick, 1000); })(); return time; }); // Notice that you can simply ask for time // and it will be provided. No need to look for it. function ClockCtrl($scope, time) { $scope.time = time; } </file> </example> <a name="angular_namespace"></a> # Angular Namespace To prevent accidental name collision, Angular prefixes names of objects which could potentially collide with `$`. Please do not use the `$` prefix in your code as it may accidentally collide with Angular code.