Mercurial > public > sg101
comparison custom_search/views.py @ 961:840c1a8bd8af
Mitigate QueryParserError when searching.
author | Brian Neal <bgneal@gmail.com> |
---|---|
date | Mon, 03 Aug 2015 17:26:32 -0500 |
parents | 20a3bf7a6370 |
children | e932f2ecd4a7 |
comparison
equal
deleted
inserted
replaced
959:fc4a1c4e488a | 961:840c1a8bd8af |
---|---|
1 """Custom views for searching.""" | 1 """Custom views for searching.""" |
2 import logging | |
2 | 3 |
4 from django.shortcuts import render_to_response | |
3 from haystack.views import SearchView | 5 from haystack.views import SearchView |
6 from xapian import QueryParserError | |
4 | 7 |
8 logger = logging.getLogger(__name__) | |
5 | 9 |
6 class UserSearchView(SearchView): | 10 class UserSearchView(SearchView): |
7 """This class passes the user making the search as an __init__ argument to | 11 """This class passes the user making the search as an __init__ argument to |
8 the search form as the keyword argument 'user'. | 12 the search form as the keyword argument 'user'. |
9 | 13 |
10 """ | 14 """ |
15 query_parser_error = False | |
16 | |
11 def build_form(self, form_kwargs=None): | 17 def build_form(self, form_kwargs=None): |
12 """Pass the request.user object to the form's constructor.""" | 18 """Pass the request.user object to the form's constructor.""" |
13 if not form_kwargs: | 19 if not form_kwargs: |
14 form_kwargs = {} | 20 form_kwargs = {} |
15 if 'user' not in form_kwargs: | 21 if 'user' not in form_kwargs: |
16 form_kwargs['user'] = self.request.user | 22 form_kwargs['user'] = self.request.user |
17 return super(UserSearchView, self).build_form(form_kwargs) | 23 return super(UserSearchView, self).build_form(form_kwargs) |
24 | |
25 # This nonsense is because Xapian can raise QueryParserError when evaluating | |
26 # the query. This was triggered by some sh*t-bag looking for SQL injection | |
27 # vulnerabilities. | |
28 # If QueryParserError is raised, just drive on and set a flag in the context | |
29 # (via extra_context()) so that an error is rendered on the template instead | |
30 # of a 500 error. | |
31 | |
32 def create_response(self): | |
33 try: | |
34 return super(UserSearchView, self).create_response() | |
35 except QueryParserError: | |
36 self.query_parser_error = True | |
37 | |
38 logger.warning("QueryParserError triggered from user search input") | |
39 | |
40 context = { | |
41 'query': self.query, | |
42 'form': self.form, | |
43 'page': None, | |
44 'paginator': None, | |
45 'suggestion': None, | |
46 } | |
47 | |
48 context.update(self.extra_context()) | |
49 return render_to_response(self.template, context, | |
50 context_instance=self.context_class(self.request)) | |
51 | |
52 def extra_context(self): | |
53 return { | |
54 'query_parser_error': self.query_parser_error, | |
55 } |