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

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 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)