~ben-a/u1db/fixes--1262956

« back to all changes in this revision

Viewing changes to u1db/remote/cors_middleware.py

  • Committer: Tarmac
  • Author(s): Samuele Pedroni (Canonical Services Ltd.)
  • Date: 2012-10-10 19:55:29 UTC
  • mfrom: (424.2.2 cors-middleware)
  • Revision ID: tarmac-20121010195529-oxr9ci4u7w4yslcg
add CORS middleware

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright 2012 Canonical Ltd.
 
2
#
 
3
# This file is part of u1db.
 
4
#
 
5
# u1db is free software: you can redistribute it and/or modify
 
6
# it under the terms of the GNU Lesser General Public License version 3
 
7
# as published by the Free Software Foundation.
 
8
#
 
9
# u1db is distributed in the hope that it will be useful,
 
10
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
11
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
12
# GNU Lesser General Public License for more details.
 
13
#
 
14
# You should have received a copy of the GNU Lesser General Public License
 
15
# along with u1db.  If not, see <http://www.gnu.org/licenses/>.
 
16
"""U1DB Cross-Origin Resource Sharing WSGI middleware."""
 
17
 
 
18
 
 
19
class CORSMiddleware(object):
 
20
    """U1DB Cross-Origin Resource Sharing WSGI middleware."""
 
21
 
 
22
    def __init__(self, app, accept_cors_connections):
 
23
        self.origins = ' '.join(accept_cors_connections)
 
24
        self.app = app
 
25
 
 
26
    def _cors_headers(self):
 
27
        return [('access-control-allow-origin', self.origins),
 
28
                ('access-control-allow-headers',
 
29
                 'authorization, content-type'),
 
30
                ('access-control-allow-methods',
 
31
                 'GET, POST, PUT, DELETE, OPTIONS')]
 
32
 
 
33
    def __call__(self, environ, start_response):
 
34
        def wrap_start_response(status, headers, exc_info=None):
 
35
            headers += self._cors_headers()
 
36
            return start_response(status, headers, exc_info)
 
37
 
 
38
        if environ['REQUEST_METHOD'].lower() == 'options':
 
39
            wrap_start_response("200 OK", [('content-type', 'text/plain')])
 
40
            return ['']
 
41
 
 
42
        return self.app(environ, wrap_start_response)