|
4 | 4 | from django.core.files.storage import default_storage |
5 | 5 | from elasticsearch import Elasticsearch |
6 | 6 | from rest_framework.authentication import TokenAuthentication |
7 | | -from rest_framework.decorators import api_view, authentication_classes, permission_classes |
| 7 | +from rest_framework.decorators import api_view, authentication_classes, permission_classes, throttle_classes |
8 | 8 | from rest_framework.permissions import IsAuthenticated |
9 | 9 | from rest_framework.response import Response |
| 10 | +from rest_framework.throttling import UserRateThrottle |
10 | 11 |
|
11 | 12 | from bazaar.core.tasks import analyze |
12 | 13 | from bazaar.core.utils import get_sha256_of_file |
| 14 | +from bazaar.front.utils import transform_hl_results |
13 | 15 |
|
14 | 16 |
|
15 | 17 | @api_view(['GET', 'POST']) |
@@ -65,3 +67,40 @@ def analysis_tasks_status(request, sha256): |
65 | 67 | except Exception as e: |
66 | 68 | logging.exception(e) |
67 | 69 | return Response({"error": "Object of type NotFoundError is not JSON serializable"}) |
| 70 | + |
| 71 | + |
| 72 | +@api_view(['POST']) |
| 73 | +@authentication_classes([TokenAuthentication]) |
| 74 | +@permission_classes([IsAuthenticated]) |
| 75 | +@throttle_classes([UserRateThrottle]) |
| 76 | +def search(request): |
| 77 | + user_query = request.data |
| 78 | + if not user_query or 'q' not in user_query: |
| 79 | + return Response([]) |
| 80 | + q = user_query.get('q') |
| 81 | + query = { |
| 82 | + "query": { |
| 83 | + "query_string": { |
| 84 | + "default_field": "sha256", |
| 85 | + "query": q |
| 86 | + } |
| 87 | + }, |
| 88 | + "highlight": { |
| 89 | + "fields": { |
| 90 | + "*": {"pre_tags": ["<mark>"], "post_tags": ["</mark>"]} |
| 91 | + } |
| 92 | + }, |
| 93 | + "sort": {"analysis_date": "desc"}, |
| 94 | + "_source": ["sha256", "uploaded_at", "handle", "app_name", |
| 95 | + "version_code", "size", "dexofuzzy.apk", "quark.threat_level", "vt", "malware_bazaar", |
| 96 | + "is_signed", "frosting_data.is_frosted", "features"], |
| 97 | + "size": 150, |
| 98 | + } |
| 99 | + |
| 100 | + es = Elasticsearch(settings.ELASTICSEARCH_HOSTS) |
| 101 | + try: |
| 102 | + raw_results = es.search(index=settings.ELASTICSEARCH_APK_INDEX, body=query) |
| 103 | + results = transform_hl_results(raw_results) |
| 104 | + return Response(results) |
| 105 | + except Exception as e: |
| 106 | + return Response([]) |
0 commit comments