<commit_before>from django.apps import apps
from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Permission
from django.contrib.sites.models import Site
from django.core.exceptions import ObjectDoesNotExist
from django.db.models import Q
import logging
from janeus import Janeus
from janeus.models import JaneusUser, JaneusRole

logger = logging.getLogger(__name__)


class JaneusBackend(object):
    @staticmethod
    def login(username, password):
        if hasattr(settings, 'JANEUS_FAKE_LDAP'):
            return True if settings.JANEUS_FAKE_LDAP(username, password) is not None else False
        else:
            logger.info('Trying to authenticate {} in LDAP'.format(username))

            # get dn of user
            res = Janeus().by_uid(username)
            if res is None:
                return False
            dn, attrs = res

            # try to login
            return Janeus().test_login(dn, password)

    @staticmethod
    def get_attrs_groups(username):
        if hasattr(settings, 'JANEUS_FAKE_LDAP'):
            return None, settings.JANEUS_FAKE_LDAP(username, None)
        else:
            # get dn of user
            res = Janeus().by_uid(username)
            if res is None:
                return None, None
            dn, attrs = res

            # get groups of dn
            return attrs, Janeus().groups_of_dn(dn)

    @staticmethod
    def current_site_id():
        if hasattr(settings, 'JANEUS_CURRENT_SITE'):
            site = settings.JANEUS_CURRENT_SITE()
            return site.id if isinstance(site, Site) else site
        elif apps.is_installed('mezzanine.core'):
            from mezzanine.utils.sites import current_site_id
            return current_site_id()
        else:
            from django.contrib.sites.shortcuts import get_current_site
            site = get_current_site()
            return site.id if isinstance(site, Site) else None

    def authenticate(self, username=None, password=<PASSWORD>):
        # authenticate
        if not JaneusBackend.login(username, password):
            return None

        # get LDAP attributes and groups of user
        attrs, groups = JaneusBackend.get_attrs_groups(username)
        groups = groups or []
        if len(groups) == 0:
            return None

        # find all roles of this user, if any
        roles = JaneusRole.objects.filter(role__in=groups)
        if len(roles) == 0:
            return None

        # determine the sites user has any access to
        if len(roles.filter(sites=None)) > 0:
            # user has access to all sites
            sites = Site.objects.all()
        else:
            # user has access to some sites
            sites_query = '{}__in'.format(JaneusRole._meta.get_field('sites').related_query_name())
            sites = Site.objects.filter(**{sites_query: roles})

        # find current site
        site = JaneusBackend.current_site_id()
        if site is not None:
            # check if user gets access
            if site not in [s.pk for s in sites]:
                return None
            # restrict roles to roles of the current site
            roles = roles.filter(Q(sites=None) | Q(sites__id__exact=site))

        # get or create JaneusUser object
        try:
            juser = JaneusUser.objects.get(uid=username)
        except JaneusUser.DoesNotExist:
            juser = JaneusUser(uid=username, user=None)
            juser.save()

        # get or create User
        if juser.user is None:
            model = get_user_model()
            username_field = getattr(model, 'USERNAME_FIELD', 'username')

            kwargs = {
                username_field + '__iexact': username,
                'defaults': {username_field: username.lower()}
            }

            juser.user, created = model.objects.get_or_create(**kwargs)
            if created:
                # created, so set active, staff, unusable password
                juser.user.set_unusable_password()
                juser.user.is_active = True
                juser.user.is_staff = True
                juser.user.save()
            juser.save()

        # now update attributes of user
        if attrs is not None:
            setattr(juser.user, 'last_name', attrs['sn'][0])
            setattr(juser.user, 'email', attrs['mail'][0])
            juser.user.save()

        # Mezzanine support
        if apps.is_installed('mezzanine.core'):
            from mezzanine.core.models import SitePermission
            # we do not remove site permission objects, we only add them
            sp, created = SitePermission.objects.get_or_create(user=juser.user)
            sp.sites.add(*sites)
            sp.save()

        # add information to User object
        juser.user._janeus_user = juser
        juser.user._janeus_groups = groups
        juser.user._janeus_roles = roles  # all roles of current site
        juser.user._janeus_sites = sites  # all sites with access
<commit_msg>Add option to clear mezzanine SitePermission sites on login<commit_after>from django.apps import apps
from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Permission
from django.contrib.sites.models import Site
from django.core.exceptions import ObjectDoesNotExist
from django.db.models import Q
import logging
from janeus import Janeus
from janeus.models import JaneusUser, JaneusRole

logger = logging.getLogger(__name__)


class JaneusBackend(object):
    @staticmethod
    def login(username, password):
        if hasattr(settings, 'JANEUS_FAKE_LDAP'):
            return True if settings.JANEUS_FAKE_LDAP(username, password) is not None else False
        else:
            logger.info('Trying to authenticate {} in LDAP'.format(username))

            # get dn of user
            res = Janeus().by_uid(username)
            if res is None:
                return False
            dn, attrs = res

            # try to login
            return Janeus().test_login(dn, password)

    @staticmethod
    def get_attrs_groups(username):
        if hasattr(settings, 'JANEUS_FAKE_LDAP'):
            return None, settings.JANEUS_FAKE_LDAP(username, None)
        else:
            # get dn of user
            res = Janeus().by_uid(username)
            if res is None:
                return None, None
            dn, attrs = res

            # get groups of dn
            return attrs, Janeus().groups_of_dn(dn)

    @staticmethod
    def current_site_id():
        if hasattr(settings, 'JANEUS_CURRENT_SITE'):
            site = settings.JANEUS_CURRENT_SITE()
            return site.id if isinstance(site, Site) else site
        elif apps.is_installed('mezzanine.core'):
            from mezzanine.utils.sites import current_site_id
            return current_site_id()
        else:
            from django.contrib.sites.shortcuts import get_current_site
            site = get_current_site()
            return site.id if isinstance(site, Site) else None

    def authenticate(self, username=None, password=<PASSWORD>):
        # authenticate
        if not JaneusBackend.login(username, password):
            return None

        # get LDAP attributes and groups of user
        attrs, groups = JaneusBackend.get_attrs_groups(username)
        groups = groups or []
        if len(groups) == 0:
            return None

        # find all roles of this user, if any
        roles = JaneusRole.objects.filter(role__in=groups)
        if len(roles) == 0:
            return None

        # determine the sites user has any access to
        if len(roles.filter(sites=None)) > 0:
            # user has access to all sites
            sites = Site.objects.all()
        else:
            # user has access to some sites
            sites_query = '{}__in'.format(JaneusRole._meta.get_field('sites').related_query_name())
            sites = Site.objects.filter(**{sites_query: roles})

        # find current site
        site = JaneusBackend.current_site_id()
        if site is not None:
            # check if user gets access
            if site not in [s.pk for s in sites]:
                return None
            # restrict roles to roles of the current site
            roles = roles.filter(Q(sites=None) | Q(sites__id__exact=site))

        # get or create JaneusUser object
        try:
            juser = JaneusUser.objects.get(uid=username)
        except JaneusUser.DoesNotExist:
            juser = JaneusUser(uid=username, user=None)
            juser.save()

        # get or create User
        if juser.user is None:
            model = get_user_model()
            username_field = getattr(model, 'USERNAME_FIELD', 'username')

            kwargs = {
                username_field + '__iexact': username,
                'defaults': {username_field: username.lower()}
            }

            juser.user, created = model.objects.get_or_create(**kwargs)
            if created:
                # created, so set active, staff, unusable password
                juser.user.set_unusable_password()
                juser.user.is_active = True
                juser.user.is_staff = True
                juser.user.save()
            juser.save()

        # now update attributes of user
        if attrs is not None:
            setattr(juser.user, 'last_name', attrs['sn'][0])
            setattr(juser.user, 'email', attrs['mail'][0])
            juser.user.save()

        # Mezzanine support
        if apps.is_installed('mezzanine.core'):
            from mezzanine.core.models import SitePermission
            sp, created = SitePermission.objects.get_or_create(user=juser.user)
            # if set in the settings, clear sp.sites before adding site permissions
            if getattr(settings, 'JANEUS_MEZZANINE_CLEAR_SITEPERMISSION', False):
                sp.sites.clear()
            sp.sites.add(*sites)
            sp.save()

        # add information to User object
        juser.user._janeus_user = juser
        juser.user._janeus_groups = groups
        juser.user._janeus_roles = roles  # all roles of current site
        juser.user._janeus_sites = sites  # all sites with access

{'fraction_non_alphanumeric': 0.0812451057165231, 'fraction_numerical': 0.0009788566953797965, 'mean_word_length': 2.0398690865813744, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 7, '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': '1409422', 'n_tokens_mistral': 2900, 'n_tokens_neox': 2794, 'n_words': 787}