Python django.contrib.auth.get_backends() Examples

The following are 30 code examples of django.contrib.auth.get_backends(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.contrib.auth , or try the search function .
Example #1
Source File: orm_driver.py    From django-river with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _authorized_approvals(self, as_user):
        group_q = Q()
        for g in as_user.groups.all():
            group_q = group_q | Q(groups__in=[g])

        permissions = []
        for backend in auth.get_backends():
            permissions.extend(backend.get_all_permissions(as_user))

        permission_q = Q()
        for p in permissions:
            label, codename = p.split('.')
            permission_q = permission_q | Q(permissions__content_type__app_label=label,
                                            permissions__codename=codename)

        return TransitionApproval.objects.filter(
            Q(workflow=self.workflow, status=PENDING) &
            (
                    (Q(transactioner__isnull=True) | Q(transactioner=as_user)) &
                    (Q(permissions__isnull=True) | permission_q) &
                    (Q(groups__isnull=True) | group_q)
            )
        ) 
Example #2
Source File: remote_user.py    From django-keycloak with MIT License 6 votes vote down vote up
def has_perm(self, perm, obj=None):
        """
        Logic from django.contrib.auth.models._user_has_perm
        :param perm:
        :param obj:
        :return:
        """
        for backend in auth.get_backends():
            if not hasattr(backend, 'has_perm') \
                    or backend.__module__.startswith('django.contrib.auth'):
                continue
            try:
                if backend.has_perm(self, perm, obj):
                    return True
            except PermissionDenied:
                return False
        return False 
Example #3
Source File: backends.py    From zulip with Apache License 2.0 6 votes vote down vote up
def query_ldap(email: str) -> List[str]:
    values = []
    backend = next((backend for backend in get_backends() if isinstance(backend, LDAPBackend)), None)
    if backend is not None:
        try:
            ldap_username = backend.django_to_ldap_username(email)
        except ZulipLDAPExceptionNoMatchingLDAPUser as e:
            values.append(f"No such user found: {e}")
            return values

        ldap_attrs = _LDAPUser(backend, ldap_username).attrs

        for django_field, ldap_field in settings.AUTH_LDAP_USER_ATTR_MAP.items():
            value = ldap_attrs.get(ldap_field, ["LDAP field not present"])[0]
            if django_field == "avatar":
                if isinstance(value, bytes):
                    value = "(An avatar image file)"
            values.append(f"{django_field}: {value}")
        if settings.LDAP_EMAIL_ATTR is not None:
            values.append("{}: {}".format('email', ldap_attrs[settings.LDAP_EMAIL_ATTR][0]))
    else:
        values.append("LDAP backend not configured on this server.")
    return values 
Example #4
Source File: models.py    From django-protector with MIT License 6 votes vote down vote up
def has_module_perms(self, app_label):
        """
        Returns True if the user has any permissions in the given app label.
        Uses pretty much the same logic as has_perm, above.
        """
        if self.is_active and self.is_superuser:
            return True

        for backend in auth.get_backends():
            if not hasattr(backend, 'has_module_perms'):
                continue
            try:
                if backend.has_module_perms(self, app_label):
                    return True
            except PermissionDenied:
                return False
        return False 
Example #5
Source File: models.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
def get_group_permissions(self, obj=None):
        """
        Returns a list of permission strings that this user has through their
        groups. This method queries all available auth backends. If an object
        is passed in, only permissions matching this object are returned.
        """
        permissions = set()
        for backend in auth.get_backends():
            if hasattr(backend, "get_group_permissions"):
                permissions.update(backend.get_group_permissions(self, obj))
        return permissions 
Example #6
Source File: models.py    From Hands-On-Application-Development-with-PyCharm with MIT License 5 votes vote down vote up
def get_group_permissions(self, obj=None):
        """
        Return a list of permission strings that this user has through their
        groups. Query all available auth backends. If an object is passed in,
        return only permissions matching this object.
        """
        permissions = set()
        for backend in auth.get_backends():
            if hasattr(backend, "get_group_permissions"):
                permissions.update(backend.get_group_permissions(self, obj))
        return permissions 
Example #7
Source File: models.py    From django-protector with MIT License 5 votes vote down vote up
def has_perm(self, perm, obj=None):
        if self.is_active and self.is_superuser:
            return True

        for backend in auth.get_backends():
            if not hasattr(backend, 'has_perm'):
                continue
            try:
                if backend.has_perm(self, perm, obj):
                    return True
            except PermissionDenied:
                return False
        return False 
Example #8
Source File: models.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
def _user_get_all_permissions(user, obj):
    permissions = set()
    for backend in auth.get_backends():
        if hasattr(backend, "get_all_permissions"):
            permissions.update(backend.get_all_permissions(user, obj))
    return permissions 
Example #9
Source File: models.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
def _user_has_perm(user, perm, obj):
    """
    A backend can raise `PermissionDenied` to short-circuit permission checking.
    """
    for backend in auth.get_backends():
        if not hasattr(backend, 'has_perm'):
            continue
        try:
            if backend.has_perm(user, perm, obj):
                return True
        except PermissionDenied:
            return False
    return False 
Example #10
Source File: models.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
def _user_has_module_perms(user, app_label):
    """
    A backend can raise `PermissionDenied` to short-circuit permission checking.
    """
    for backend in auth.get_backends():
        if not hasattr(backend, 'has_module_perms'):
            continue
        try:
            if backend.has_module_perms(user, app_label):
                return True
        except PermissionDenied:
            return False
    return False 
Example #11
Source File: models.py    From Hands-On-Application-Development-with-PyCharm with MIT License 5 votes vote down vote up
def _user_has_perm(user, perm, obj):
    """
    A backend can raise `PermissionDenied` to short-circuit permission checking.
    """
    for backend in auth.get_backends():
        if not hasattr(backend, 'has_perm'):
            continue
        try:
            if backend.has_perm(user, perm, obj):
                return True
        except PermissionDenied:
            return False
    return False 
Example #12
Source File: models.py    From python2017 with MIT License 5 votes vote down vote up
def _user_get_all_permissions(user, obj):
    permissions = set()
    for backend in auth.get_backends():
        if hasattr(backend, "get_all_permissions"):
            permissions.update(backend.get_all_permissions(user, obj))
    return permissions 
Example #13
Source File: models.py    From python2017 with MIT License 5 votes vote down vote up
def _user_has_perm(user, perm, obj):
    """
    A backend can raise `PermissionDenied` to short-circuit permission checking.
    """
    for backend in auth.get_backends():
        if not hasattr(backend, 'has_perm'):
            continue
        try:
            if backend.has_perm(user, perm, obj):
                return True
        except PermissionDenied:
            return False
    return False 
Example #14
Source File: models.py    From python2017 with MIT License 5 votes vote down vote up
def _user_has_module_perms(user, app_label):
    """
    A backend can raise `PermissionDenied` to short-circuit permission checking.
    """
    for backend in auth.get_backends():
        if not hasattr(backend, 'has_module_perms'):
            continue
        try:
            if backend.has_module_perms(user, app_label):
                return True
        except PermissionDenied:
            return False
    return False 
Example #15
Source File: models.py    From python2017 with MIT License 5 votes vote down vote up
def get_group_permissions(self, obj=None):
        """
        Returns a list of permission strings that this user has through their
        groups. This method queries all available auth backends. If an object
        is passed in, only permissions matching this object are returned.
        """
        permissions = set()
        for backend in auth.get_backends():
            if hasattr(backend, "get_group_permissions"):
                permissions.update(backend.get_group_permissions(self, obj))
        return permissions 
Example #16
Source File: remote_user.py    From django-keycloak with MIT License 5 votes vote down vote up
def get_all_permissions(self, obj=None):
        """
        Logic from django.contrib.auth.models._user_get_all_permissions
        :param perm:
        :param obj:
        :return:
        """
        permissions = set()
        for backend in auth.get_backends():
            # Excluding Django.contrib.auth backends since they are not
            # compatible with non-db-backed permissions.
            if hasattr(backend, "get_all_permissions") \
                    and not backend.__module__.startswith('django.'):
                permissions.update(backend.get_all_permissions(self, obj))
        return permissions 
Example #17
Source File: remote_user.py    From django-keycloak with MIT License 5 votes vote down vote up
def has_module_perms(self, module):
        """
        Logic from django.contrib.auth.models._user_has_module_perms
        :param module:
        :return:
        """
        for backend in auth.get_backends():
            if not hasattr(backend, 'has_module_perms'):
                continue
            try:
                if backend.has_module_perms(self, module):
                    return True
            except PermissionDenied:
                return False
        return False 
Example #18
Source File: models.py    From Hands-On-Application-Development-with-PyCharm with MIT License 5 votes vote down vote up
def _user_has_module_perms(user, app_label):
    """
    A backend can raise `PermissionDenied` to short-circuit permission checking.
    """
    for backend in auth.get_backends():
        if not hasattr(backend, 'has_module_perms'):
            continue
        try:
            if backend.has_module_perms(user, app_label):
                return True
        except PermissionDenied:
            return False
    return False 
Example #19
Source File: models.py    From Hands-On-Application-Development-with-PyCharm with MIT License 5 votes vote down vote up
def _user_get_all_permissions(user, obj):
    permissions = set()
    for backend in auth.get_backends():
        if hasattr(backend, "get_all_permissions"):
            permissions.update(backend.get_all_permissions(user, obj))
    return permissions 
Example #20
Source File: drf.py    From mozilla-django-oidc with Mozilla Public License 2.0 5 votes vote down vote up
def get_oidc_backend():
    """
    Get the Django auth backend that uses OIDC.
    """

    # allow the user to force which back backend to use. this is mostly
    # convenient if you want to use OIDC with DRF but don't want to configure
    # OIDC for the "normal" Django auth.
    backend_setting = import_from_settings('OIDC_DRF_AUTH_BACKEND', None)
    if backend_setting:
        backend = import_string(backend_setting)()
        if not isinstance(backend, OIDCAuthenticationBackend):
            msg = 'Class configured in OIDC_DRF_AUTH_BACKEND ' \
                  'does not extend OIDCAuthenticationBackend!'
            raise ImproperlyConfigured(msg)
        return backend

    # if the backend setting is not set, look through the list of configured
    # backends for one that is an OIDCAuthenticationBackend.
    backends = [b for b in get_backends() if isinstance(b, OIDCAuthenticationBackend)]

    if not backends:
        msg = 'No backends extending OIDCAuthenticationBackend found - ' \
              'add one to AUTHENTICATION_BACKENDS or set OIDC_DRF_AUTH_BACKEND!'
        raise ImproperlyConfigured(msg)
    if len(backends) > 1:
        raise ImproperlyConfigured('More than one OIDCAuthenticationBackend found!')
    return backends[0] 
Example #21
Source File: profile.py    From pasportaservo with GNU Affero General Public License v3.0 5 votes vote down vote up
def supervisor_of(user_or_profile):
    user = _convert_profile_to_user(user_or_profile)
    if auth_log.getEffectiveLevel() == logging.DEBUG:
        auth_log.debug(
            "* searching supervised objects... [ %s %s]",
            user, "<~ '%s' " % user_or_profile if user != user_or_profile else "")
    for backend in auth.get_backends():
        try:
            return sorted(backend.get_user_supervisor_of(user))
        except Exception:
            pass
    return ("",) 
Example #22
Source File: profile.py    From pasportaservo with GNU Affero General Public License v3.0 5 votes vote down vote up
def is_supervisor_of(user_or_profile, profile_or_countries):
    user = _convert_profile_to_user(user_or_profile)
    if auth_log.getEffectiveLevel() == logging.DEBUG:
        auth_log.debug(
            "* checking if object is supervised... [ %s %s] [ %s ]",
            user, "<~ '%s' " % user_or_profile if user != user_or_profile else "",
            repr(profile_or_countries))
    if isinstance(profile_or_countries, int):
        try:
            profile_or_countries = Profile.objects.get(pk=profile_or_countries)
        except Profile.DoesNotExist:
            return False
    elif isinstance(profile_or_countries, str):
        profile_or_countries = profile_or_countries.split(" ")

    # supervisor = False
    # for backend in auth.get_backends():
    #     try:
    #         supervisor = backend.is_user_supervisor_of(user, profile_or_countries)
    #     except AttributeError as e:
    #         pass
    #     except:
    #         supervisor = False
    #     else:
    #         break
    # return supervisor
    return user.has_perm(PERM_SUPERVISOR, profile_or_countries) 
Example #23
Source File: models.py    From bioforum with MIT License 5 votes vote down vote up
def get_group_permissions(self, obj=None):
        """
        Return a list of permission strings that this user has through their
        groups. Query all available auth backends. If an object is passed in,
        return only permissions matching this object.
        """
        permissions = set()
        for backend in auth.get_backends():
            if hasattr(backend, "get_group_permissions"):
                permissions.update(backend.get_group_permissions(self, obj))
        return permissions 
Example #24
Source File: models.py    From bioforum with MIT License 5 votes vote down vote up
def _user_has_module_perms(user, app_label):
    """
    A backend can raise `PermissionDenied` to short-circuit permission checking.
    """
    for backend in auth.get_backends():
        if not hasattr(backend, 'has_module_perms'):
            continue
        try:
            if backend.has_module_perms(user, app_label):
                return True
        except PermissionDenied:
            return False
    return False 
Example #25
Source File: models.py    From bioforum with MIT License 5 votes vote down vote up
def _user_has_perm(user, perm, obj):
    """
    A backend can raise `PermissionDenied` to short-circuit permission checking.
    """
    for backend in auth.get_backends():
        if not hasattr(backend, 'has_perm'):
            continue
        try:
            if backend.has_perm(user, perm, obj):
                return True
        except PermissionDenied:
            return False
    return False 
Example #26
Source File: models.py    From bioforum with MIT License 5 votes vote down vote up
def _user_get_all_permissions(user, obj):
    permissions = set()
    for backend in auth.get_backends():
        if hasattr(backend, "get_all_permissions"):
            permissions.update(backend.get_all_permissions(user, obj))
    return permissions 
Example #27
Source File: tests.py    From django-auth-ldap with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def get_backend():
    backends = get_backends()
    return backends[0] 
Example #28
Source File: models.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def get_group_permissions(self, obj=None):
        """
        Returns a list of permission strings that this user has through their
        groups. This method queries all available auth backends. If an object
        is passed in, only permissions matching this object are returned.
        """
        permissions = set()
        for backend in auth.get_backends():
            if hasattr(backend, "get_group_permissions"):
                permissions.update(backend.get_group_permissions(self, obj))
        return permissions 
Example #29
Source File: models.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def _user_has_module_perms(user, app_label):
    """
    A backend can raise `PermissionDenied` to short-circuit permission checking.
    """
    for backend in auth.get_backends():
        if not hasattr(backend, 'has_module_perms'):
            continue
        try:
            if backend.has_module_perms(user, app_label):
                return True
        except PermissionDenied:
            return False
    return False 
Example #30
Source File: models.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def _user_has_perm(user, perm, obj):
    """
    A backend can raise `PermissionDenied` to short-circuit permission checking.
    """
    for backend in auth.get_backends():
        if not hasattr(backend, 'has_perm'):
            continue
        try:
            if backend.has_perm(user, perm, obj):
                return True
        except PermissionDenied:
            return False
    return False