<commit_before># Copyright (C) 2010-2012 Yaco Sistemas (http://www.yaco.es)
# Copyright (C) 2009 <NAME> <<EMAIL>>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#            http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import logging

from django.conf import settings
from django.contrib import auth
from django.contrib.auth.backends import ModelBackend
from django.core.exceptions import (
    MultipleObjectsReturned, ImproperlyConfigured,
)

from djangosaml2.signals import pre_user_save


logger = logging.getLogger('djangosaml2')


def get_model(model_path):
    try:
        from django.apps import apps
        return apps.get_model(model_path)
    except ImportError:
        # Django < 1.7 (cannot use the new app loader)
        from django.db.models import get_model as django_get_model
        try:
            app_label, model_name = model_path.split('.')
        except ValueError:
            raise ImproperlyConfigured("SAML_USER_MODEL must be of the form "
                "'app_label.model_name'")
        user_model = django_get_model(app_label, model_name)
        if user_model is None:
            raise ImproperlyConfigured("SAML_USER_MODEL refers to model '%s' "
                "that has not been installed" % model_path)
        return user_model


def get_saml_user_model():
    try:
        # djangosaml2 custom user model
        return get_model(settings.SAML_USER_MODEL)
    except AttributeError:
        try:
            # Django 1.5 Custom user model
            return auth.get_user_model()
        except AttributeError:
            return auth.models.User


class Saml2Backend(ModelBackend):

    def authenticate(self, request, session_info=None, attribute_mapping=None,
                     create_unknown_user=True, **kwargs):
        if session_info is None or attribute_mapping is None:
            logger.error('Session info or attribute mapping are None')
            return None

        if not 'ava' in session_info:
            logger.error('"ava" key not found in session_info')
            return None

        attributes = self.clean_attributes(session_info['ava'])
        if not attributes:
            logger.error('The attributes dictionary is empty')

        use_name_id_as_username = getattr(
            settings, 'SAML_USE_NAME_ID_AS_USERNAME', False)

        django_user_main_attribute = self.get_django_user_main_attribute()

        logger.debug('attributes: %s', attributes)
        saml_user = None
        if use_name_id_as_username:
            if 'name_id' in session_info:
                logger.debug('name_id: %s', session_info['name_id'])
                saml_user = session_info['name_id'].text
            else:
                logger.error('The nameid is not available. Cannot find user without a nameid.')
        else:
            saml_user = self.get_attribute_value(django_user_main_attribute, attributes, attribute_mapping)

        if saml_user is None:
            logger.error('Could not find saml_user value')
            return None

        if not self.is_authorized(attributes, attribute_mapping):
            return None

        main_attribute = self.clean_user_main_attribute(saml_user)<commit_msg>Logger for non-saml2 authentication attempts from error to info<commit_after># Copyright (C) 2010-2012 Yaco Sistemas (http://www.yaco.es)
# Copyright (C) 2009 <NAME> <<EMAIL>>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#            http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import logging

from django.conf import settings
from django.contrib import auth
from django.contrib.auth.backends import ModelBackend
from django.core.exceptions import (
    MultipleObjectsReturned, ImproperlyConfigured,
)

from djangosaml2.signals import pre_user_save


logger = logging.getLogger('djangosaml2')


def get_model(model_path):
    try:
        from django.apps import apps
        return apps.get_model(model_path)
    except ImportError:
        # Django < 1.7 (cannot use the new app loader)
        from django.db.models import get_model as django_get_model
        try:
            app_label, model_name = model_path.split('.')
        except ValueError:
            raise ImproperlyConfigured("SAML_USER_MODEL must be of the form "
                "'app_label.model_name'")
        user_model = django_get_model(app_label, model_name)
        if user_model is None:
            raise ImproperlyConfigured("SAML_USER_MODEL refers to model '%s' "
                "that has not been installed" % model_path)
        return user_model


def get_saml_user_model():
    try:
        # djangosaml2 custom user model
        return get_model(settings.SAML_USER_MODEL)
    except AttributeError:
        try:
            # Django 1.5 Custom user model
            return auth.get_user_model()
        except AttributeError:
            return auth.models.User


class Saml2Backend(ModelBackend):

    def authenticate(self, request, session_info=None, attribute_mapping=None,
                     create_unknown_user=True, **kwargs):
        if session_info is None or attribute_mapping is None:
            logger.info('Session info or attribute mapping are None')
            return None

        if 'ava' not in session_info:
            logger.error('"ava" key not found in session_info')
            return None

        attributes = self.clean_attributes(session_info['ava'])
        if not attributes:
            logger.error('The attributes dictionary is empty')

        use_name_id_as_username = getattr(
            settings, 'SAML_USE_NAME_ID_AS_USERNAME', False)

        django_user_main_attribute = self.get_django_user_main_attribute()

        logger.debug('attributes: %s', attributes)
        saml_user = None
        if use_name_id_as_username:
            if 'name_id' in session_info:
                logger.debug('name_id: %s', session_info['name_id'])
                saml_user = session_info['name_id'].text
            else:
                logger.error('The nameid is not available. Cannot find user without a nameid.')
        else:
            saml_user = self.get_attribute_value(django_user_main_attribute, attributes, attribute_mapping)

        if saml_user is None:
            logger.error('Could not find saml_user value')
            return None

        if not self.is_authorized(attributes, attribute_mapping):
            return None

        main_attribute = self.clean_user_main_attribute(saml_user)
{'fraction_non_alphanumeric': 0.07196504164959716, 'fraction_numerical': 0.006691246756793664, 'mean_word_length': 2.752049180327869, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 9, 'https://': 0, 'lorem ipsum': 0, 'www.': 4, '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': '6475576', 'n_tokens_mistral': 2065, 'n_tokens_neox': 1983, 'n_words': 623}