# -*- coding: utf-8 -*-
from __future__ import unicode_literals

import logging

from django.conf import settings
from django.core import exceptions


logger = logging.getLogger(__name__)


class CertificateMiddleware(object):
    """
    Валидируем клиентские сертификаты, где это необходимо
    https://doc.qloud.yandex-team.ru/doc/domain
    """
    # Copy-pasted from django_idm_api. There are some uncertainties
    # with Verified values. We use this object until they are resolved.
    # TODO(remedy) Switch to django_idm_api when it's fixed.

    def process_request(self, request):
        if request.path.startswith('/' + settings.IDM_URL_PREFIX):
            ssl_verified = request.META.get('HTTP_X_QLOUD_SSL_VERIFIED')
            ssl_subject = request.META.get('HTTP_X_QLOUD_SSL_SUBJECT')
            ssl_issuer = request.META.get('HTTP_X_QLOUD_SSL_ISSUER')
            logger.info('X-Qloud-SSL-Verified: %s', ssl_verified)
            logger.info('X-Qloud-SSL-Issuer: %s', ssl_issuer)
            logger.info('X-Qloud-SSL-Subject: %s', ssl_subject)
            if not (ssl_verified == settings.IDM_VERIFIED_VALUE
                    and ssl_subject in settings.IDM_CERT_SUBJECTS
                    and ssl_issuer in settings.IDM_CERT_ISSUERS):
                raise exceptions.PermissionDenied(
                    'Invalid IDM client certificate'
                )
