More verbose error when AJAX request to RH fails
[cds-indico.git] / indico / web / util.py
blobd88d1f3d172437afb1ec68a66705a10a88c4d053
1 # This file is part of Indico.
2 # Copyright (C) 2002 - 2015 European Organization for Nuclear Research (CERN).
4 # Indico is free software; you can redistribute it and/or
5 # modify it under the terms of the GNU General Public License as
6 # published by the Free Software Foundation; either version 3 of the
7 # License, or (at your option) any later version.
9 # Indico is distributed in the hope that it will be useful, but
10 # WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 # General Public License for more details.
14 # You should have received a copy of the GNU General Public License
15 # along with Indico; if not, see <http://www.gnu.org/licenses/>.
17 from __future__ import absolute_import, unicode_literals
19 from flask import g, request, session, has_request_context
20 from markupsafe import Markup
23 def inject_js(js):
24 """Injects JavaScript into the current page.
26 :param js: Code wrapped in a ``<script>`` tag.
27 """
28 if 'injected_js' not in g:
29 g.injected_js = []
30 g.injected_js.append(Markup(js))
33 def _format_request_data(data, hide_passwords):
34 if not hasattr(data, 'iterlists'):
35 data = ((k, [v]) for k, v in data.iteritems())
36 else:
37 data = data.iterlists()
38 rv = {}
39 for key, values in data:
40 if hide_passwords and 'password' in key:
41 values = [v if not v else '<{} chars hidden>'.format(len(v)) for v in values]
42 rv[key] = values if len(values) != 1 else values[0]
43 return rv
46 def get_request_info(hide_passwords=True):
47 """Gets various information about the current HTTP request.
49 This is especially useful for logging purposes where you want
50 as many information as possible.
52 :param hide_passwords: Hides the actual value of POST fields
53 if their name contains ``password``.
55 :return: a dictionary containing request information, or ``None``
56 when called outside a request context
57 """
58 if not has_request_context():
59 return None
60 return {
61 'id': request.id,
62 'url': request.url,
63 'endpoint': request.url_rule.endpoint if request.url_rule else None,
64 'method': request.method,
65 'user': repr(session.user),
66 'ip': request.remote_addr,
67 'user_agent': unicode(request.user_agent),
68 'referrer': request.referrer,
69 'data': {
70 'url': _format_request_data(request.view_args, False),
71 'get': _format_request_data(request.args, False),
72 'post': _format_request_data(request.form, hide_passwords)