<commit_before>import json

from django.conf import settings
from django.http import HttpResponse

from securest.core import (OutboundMessage, InboundMessage, CertificateModel,
    Message)
from .models import CertificateModel as DjangoDB_model

# pull these from django.conf
SECUREST_DB_MODEL = DjangoDB_model
SERVER_CERTIFICATE_ID = settings.SECUREST_SERVER_CERTIFICATE_ID
SERVER_PRIVATE_KEY = settings.SECUREST_PRIVATE_KEY
PROTECT_LIST = settings.SECUREST_PROTECT_LIST


"""
Django middleware to process request and response.

Patches the `request` object by inserting `securest_decrypted` dict which
contains all the request data.
"""
class Middleware(object):
    def __init__(self):
        self.client_certificate = None

    def process_request(self, request):
        if not (request.path in PROTECT_LIST):
            return None

        prefix = 'HTTP_' + Message.prefix
        if not (prefix + 'CERTIFICATEID' in request.META):
            return None

        cert_id = request.META[prefix + 'CERTIFICATEID']
        certificate = DjangoCertificateModel.get(cert_id)
        self.client_certificate = certificate

        request_msg = InboundMessage.from_message_data(url=request.path,
            headers_dict=request.META, payload=request.body,
            certificate=certificate, local_private_key=SERVER_PRIVATE_KEY,
            is_request=True)

        if request_msg.verify_signature() == False:
            return HttpResponse('error')
        else:
            request_msg.decrypt()
            (headers, content) = request_msg.to_message_data()

            request.securest_decrypted = json.loads(content)

    def process_response(self, request, response):<commit_msg>add error handling and appropriate responses<commit_after>import json
import logging

from django.conf import settings
from django.http import HttpResponse

from securest.core import (OutboundMessage, InboundMessage, CertificateModel,
    Message)
from .models import CertificateModel as DjangoDB_model

logging.basicConfig(level=logging.INFO)

# pull these from django.conf
SECUREST_DB_MODEL = DjangoDB_model
SERVER_CERTIFICATE_ID = settings.SECUREST_SERVER_CERTIFICATE_ID
SERVER_PRIVATE_KEY = settings.SECUREST_PRIVATE_KEY
PROTECT_LIST = settings.SECUREST_PROTECT_LIST


"""
Django middleware to process request and response.

Patches the `request` object by inserting `securest_decrypted` dict which
contains all the request data.
"""
class Middleware(object):
    def __init__(self):
        self.client_certificate = None

    def process_request(self, request):
        if not (request.path in PROTECT_LIST):
            return None

        prefix = 'HTTP_' + Message.prefix
        if not (prefix + 'CERTIFICATEID' in request.META):
            return None

        cert_id = request.META[prefix + 'CERTIFICATEID']
        
        try:
            certificate = DjangoCertificateModel.get(cert_id)
        except:
            print 'here'
            certificate = None
            res = HttpResponse('Bad client certificate id.')
            res.status_code = 403
            return res

        self.client_certificate = certificate

        request_msg = InboundMessage.from_message_data(url=request.build_absolute_uri(),
            headers_dict=request.META, payload=request.body,
            certificate=certificate, local_private_key=SERVER_PRIVATE_KEY,
            is_request=True)

        sig_result = request_msg.verify_signature()
        
        if sig_result == False:
            res = HttpResponse('Bad Signature')
            res.status_code = 403
            return res
        else:
            request_msg.decrypt()
            (headers, content) = request_msg.to_message_data()
            logging.info('Request headers %s' % json.dumps(headers))

            request.securest_decrypted = json.loads(content)

    def process_response(self, request, response):
        if response.status_code == 403:
            return response

{'fraction_non_alphanumeric': 0.07177154409906494, 'fraction_numerical': 0.002274450341167551, 'mean_word_length': 3.0846233230134157, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '355619', 'n_tokens_mistral': 1133, 'n_tokens_neox': 1080, 'n_words': 264}