summaryrefslogtreecommitdiffstats
path: root/mandaye/filters/default.py
blob: 5be4cb8e7ea2a4a5d37b662197bfca40c1be05b9 (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

import re
from mandaye import config
from mandaye.backends.default import Association
from mandaye.log import logger
from mandaye.response import template_response

class MandayeFilter(object):
    """ Default Mandaye filter
    This class allows to filter the request (cookies, headers and the message-body)
    and the response (cookies, headers and message-body)
    """

    @staticmethod
    def on_request(env, values, request):
        target = env['target']
        referer = request.headers.getheader('referer')
        if referer:
            referer = referer.replace(env["HTTP_HOST"], target.hostname)
            request.headers.addheader("Referer", referer)
        origin = request.headers.getheader('origin')
        if origin:
            origin = origin.replace(env["HTTP_HOST"], target.hostname)
            request.headers.addheader("Origin", origin)
        # Add forwarded header like Apache
        request.headers.addheader('X-Forwarded-For', env['REMOTE_ADDR'])
        request.headers.addheader('X-Forwarded-Host', env['HTTP_HOST'])

    @staticmethod
    def on_response(env, values, request, response):
        target = env['target']
        # Modify cookies
        src_hostname = re.sub(":\d*$", "", env["HTTP_HOST"])
        for cookie in response.cookies.values():
            if cookie.has_key('domain'):
                cookie['domain'] = re.sub('^\.*%s$' % (target.hostname),
                        src_hostname, cookie['domain'])
        # Modify headers
        blacklist = ['transfer-encoding', 'content-length']
        for key, value in response.headers.iteritems():
            if key == 'location':
                location = value[0].replace(target.geturl(),
                        "%s://%s" % (env['mandaye.scheme'], env["HTTP_HOST"]))
                response.headers['location'] = [location]
        for name in blacklist:
            if response.headers.has_key(name):
                del response.headers[name]
        return response

    @staticmethod
    def fix_response_abs_url(env, values, request, response):
        if response.msg:
            response.msg = re.sub(r'%s[:\d]*' % env["target"].geturl(),
                    r"%s://%s" % (env["mandaye.scheme"], env["HTTP_HOST"]),
                    response.msg, flags=re.IGNORECASE)
            if env["mandaye.scheme"] == 'https':
                response.msg = response.msg.replace('http://' + env["HTTP_HOST"],
                        '%s://%s' % (env["mandaye.scheme"], env["HTTP_HOST"]))
        return response

    @staticmethod
    def add_js_header(env, values, request, response):
        if response.msg:
            if not "mjQuery = jQuery.noConflict" in response.msg:
                response.msg = re.sub(
                        r'<head(.*?)>',
                        r"""<head\1>
                <script src="%s/js/jquery-1.11.1.min.js" type="text/javascript"></script>
                <script>
                mjQuery = jQuery.noConflict( true );
                </script>""" % (config.static_url),
                response.msg, 1, re.IGNORECASE)
            scripts_html = ""
            for script in values["scripts"]:
                scripts_html += '<script src="%s/%s" charset="UTF-8" type="text/javascript"></script>' % \
                        (config.static_url, script)
            response.msg = re.sub(
                    '</head>',
                    '%s</head>' % scripts_html,
                    response.msg, 1, re.IGNORECASE)
        return response

    @staticmethod
    def addtoolbar(env, values, request, response):
        if config.mandaye_offline_toolbar or \
                env['beaker.session'].has_key('unique_id'):
            response.msg = re.sub(
                    '<head.*?>',
                """<head>
                <script src="%s/js/jquery-1.11.1.min.js" type="text/javascript"></script>
                <script>
                mjQuery = jQuery.noConflict( true );
                </script>""" % (config.static_url),
                response.msg, 1)
            response.msg = response.msg.replace(
                '</head>',
                """<script src="%s/js/toolbar.js" charset="UTF-8" type="text/javascript"></script>
                 <link rel="stylesheet" type="text/css" href="%s/css/toolbar.css">
                 </head>""" % (config.static_url, config.static_url))
        return response

    @staticmethod
    def toolbar(env, values, request, response):
        values['urls'] =  env['urls']
        values['site_name'] =  env["mandaye.config"]["site_name"]
        values['is_login'] = False
        values['is_user_locally_logged_in'] = None
        if hasattr(env['mandaye.mapper'], 'is_user_locally_logged_in'):
            values['is_user_locally_logged_in'] = env['mandaye.mapper'].\
                    is_user_locally_logged_in(env, request, response)
        current_account = None
        if env['beaker.session'].get('unique_id'):
            values['is_login'] = True
            site_name = env["mandaye.config"]["site_name"]
            if env['beaker.session'].get(site_name):
                logger.debug('toolbar there is one : %r' %\
                        env['beaker.session'].get(site_name))
                current_account = Association.get_by_id(env['beaker.session'].get(site_name))
            else:
                logger.debug('toolbar: no account')
        values['account'] = current_account
        return template_response("toolbar.html", values)