# Path: app/models.py
# class Device(models.Model):
#     """
#     Model for all device who register at the middleware.
#     """
#     # FIXME: We need this to be backwards compatible for one release.
#     id = models.CharField(max_length=255, unique=True)
# 
#     name = models.CharField(max_length=255, blank=True, null=True)
#     sip_user_id = models.CharField(max_length=255, unique=True, primary_key=True)
#     os_version = models.CharField(max_length=255, blank=True, null=True)
#     client_version = models.CharField(max_length=255, blank=True, null=True)
#     token = models.CharField(max_length=250)
#     sandbox = models.BooleanField(default=False)
#     last_seen = models.DateTimeField(blank=True, null=True)
#     app = models.ForeignKey(App)
#     remote_logging_id = models.CharField(max_length=255, blank=True, null=True)
# 
#     def __str__(self):
#         return '{0} - {1}'.format(self.sip_user_id, self.name)
# 
#     # FIXME: We need this to be backwards compatible for one release.
#     def save(self, *args, **kwargs):
#         """
#         Make sure the id fields stays the same as sip_user_id so we are
#         backwards compatible.
#         """
#         if self.sip_user_id:
#             self.id = self.sip_user_id
#             obj = super(Device, self).save(*args, **kwargs)
#             return obj
# 
# Path: app/utils.py
# LOG_EMAIL = 'email'
# 
# def log_middleware_information(log_statement, dict_with_variables, log_level, device=None):
#     """
#     Function that handles the logging for the middleware.
# 
#     Args:
#         log_statement (str): The message to log.
#         dict_with_variables (OrderedDict): OrderedDict that contains the
#             variables we want to insert into the logging statement.
#         log_level (int): The level on which to log.
#         device (Device): The device for which we want to log to Logentries.
#     """
#     remote_logging_id = device.remote_logging_id if device and device.remote_logging_id else 'No remote logging ID'
#     django_log_statement = fill_log_statement(log_statement, dict_with_variables)
#     django_logger.log(log_level, '{0} - middleware - {1}'.format(remote_logging_id, django_log_statement))
# 
#     if device and device.remote_logging_id:
#         log_statement = fill_log_statement(log_statement, dict_with_variables, anonymize=True)
#         logentries_token = device.app.logentries_token
#         log_to_logentries(log_statement, log_level, logentries_token, device, remote_logging_id)
#         if device.app.partner_logentries_token:
#             # Log to the Logentries environment of the partner with a different token.
#             logentries_token = device.app.partner_logentries_token
#             log_to_logentries(log_statement, log_level, logentries_token, device, remote_logging_id)
# 
# Path: api/exceptions.py
# class UnavailableException(APIException):
#     status_code = HTTP_503_SERVICE_UNAVAILABLE
#     default_detail = 'Service temporarily unavailable, try again later.'
# 
# Path: api/serializers.py
# class SipUserIdSerializer(serializers.Serializer):
#     """
#     Base serializer for the sip_user_id field.
#     """
#     sip_user_id = serializers.IntegerField(max_value=999999999, min_value=int(1e8))


from collections import OrderedDict
from django.conf import settings
from django.contrib.auth.models import AnonymousUser
from rest_framework.authentication import BaseAuthentication, get_authorization_header
from rest_framework.exceptions import (AuthenticationFailed, NotAuthenticated,
                                       ParseError, PermissionDenied)
from app.models import Device
from app.utils import LOG_EMAIL, log_middleware_information
from .exceptions import UnavailableException
from .serializers import SipUserIdSerializer
import logging
import requests
        if not serializer.is_valid(raise_exception=False):
            log_middleware_information(
                'BAD REQUEST! Authentication failed due to invalid sip_user_id in data:\n\n{0}',
                OrderedDict([
                    ('data', request.data),
                ]),
                logging.INFO,
            )
            # This raises a bad request response.
            raise ParseError(detail=None)

        # Get sip_user_id.
        sip_user_id = serializer.validated_data['sip_user_id']

        # Created new headers with old auth data.
        headers = {'Authorization': auth}

        # Get user profile.
        response = requests.get(settings.VG_API_USER_URL, headers=headers)
        # Check status code.
        self._check_status_code(response.status_code)

        # Parse to json.
        json_response = response.json()

        # Get app account reference on systemuser.
        app_account_url = json_response['app_account']

        if not app_account_url:
            # Has no app account and thus no access to api.

# Path: app/models.py
# class Device(models.Model):
#     """
#     Model for all device who register at the middleware.
#     """
#     # FIXME: We need this to be backwards compatible for one release.
#     id = models.CharField(max_length=255, unique=True)
# 
#     name = models.CharField(max_length=255, blank=True, null=True)
#     sip_user_id = models.CharField(max_length=255, unique=True, primary_key=True)
#     os_version = models.CharField(max_length=255, blank=True, null=True)
#     client_version = models.CharField(max_length=255, blank=True, null=True)
#     token = models.CharField(max_length=250)
#     sandbox = models.BooleanField(default=False)
#     last_seen = models.DateTimeField(blank=True, null=True)
#     app = models.ForeignKey(App)
#     remote_logging_id = models.CharField(max_length=255, blank=True, null=True)
# 
#     def __str__(self):
#         return '{0} - {1}'.format(self.sip_user_id, self.name)
# 
#     # FIXME: We need this to be backwards compatible for one release.
#     def save(self, *args, **kwargs):
#         """
#         Make sure the id fields stays the same as sip_user_id so we are
#         backwards compatible.
#         """
#         if self.sip_user_id:
#             self.id = self.sip_user_id
#             obj = super(Device, self).save(*args, **kwargs)
#             return obj
# 
# Path: app/utils.py
# LOG_EMAIL = 'email'
# 
# def log_middleware_information(log_statement, dict_with_variables, log_level, device=None):
#     """
#     Function that handles the logging for the middleware.
# 
#     Args:
#         log_statement (str): The message to log.
#         dict_with_variables (OrderedDict): OrderedDict that contains the
#             variables we want to insert into the logging statement.
#         log_level (int): The level on which to log.
#         device (Device): The device for which we want to log to Logentries.
#     """
#     remote_logging_id = device.remote_logging_id if device and device.remote_logging_id else 'No remote logging ID'
#     django_log_statement = fill_log_statement(log_statement, dict_with_variables)
#     django_logger.log(log_level, '{0} - middleware - {1}'.format(remote_logging_id, django_log_statement))
# 
#     if device and device.remote_logging_id:
#         log_statement = fill_log_statement(log_statement, dict_with_variables, anonymize=True)
#         logentries_token = device.app.logentries_token
#         log_to_logentries(log_statement, log_level, logentries_token, device, remote_logging_id)
#         if device.app.partner_logentries_token:
#             # Log to the Logentries environment of the partner with a different token.
#             logentries_token = device.app.partner_logentries_token
#             log_to_logentries(log_statement, log_level, logentries_token, device, remote_logging_id)
# 
# Path: api/exceptions.py
# class UnavailableException(APIException):
#     status_code = HTTP_503_SERVICE_UNAVAILABLE
#     default_detail = 'Service temporarily unavailable, try again later.'
# 
# Path: api/serializers.py
# class SipUserIdSerializer(serializers.Serializer):
#     """
#     Base serializer for the sip_user_id field.
#     """
#     sip_user_id = serializers.IntegerField(max_value=999999999, min_value=int(1e8))


# Path: api/authentication.py
from collections import OrderedDict
from django.conf import settings
from django.contrib.auth.models import AnonymousUser
from rest_framework.authentication import BaseAuthentication, get_authorization_header
from rest_framework.exceptions import (AuthenticationFailed, NotAuthenticated,
                                       ParseError, PermissionDenied)
from app.models import Device
from app.utils import LOG_EMAIL, log_middleware_information
from .exceptions import UnavailableException
from .serializers import SipUserIdSerializer
import logging
import requests

        if not serializer.is_valid(raise_exception=False):
            log_middleware_information(
                'BAD REQUEST! Authentication failed due to invalid sip_user_id in data:\n\n{0}',
                OrderedDict([
                    ('data', request.data),
                ]),
                logging.INFO,
            )
            # This raises a bad request response.
            raise ParseError(detail=None)

        # Get sip_user_id.
        sip_user_id = serializer.validated_data['sip_user_id']

        # Created new headers with old auth data.
        headers = {'Authorization': auth}

        # Get user profile.
        response = requests.get(settings.VG_API_USER_URL, headers=headers)
        # Check status code.
        self._check_status_code(response.status_code)

        # Parse to json.
        json_response = response.json()

        # Get app account reference on systemuser.
        app_account_url = json_response['app_account']

        if not app_account_url:
            # Has no app account and thus no access to api.

            log_middleware_information(