Python ldap.SCOPE_SUBTREE Examples

The following are 30 code examples of ldap.SCOPE_SUBTREE(). 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 ldap , or try the search function .
Example #1
Source File: ldap.py    From KubeOperator with Apache License 2.0 7 votes vote down vote up
def _search_for_user_dn(self):
        user_search_union = [
            LDAPSearch(
                USER_SEARCH, ldap.SCOPE_SUBTREE,
                settings.AUTH_LDAP_SEARCH_FILTER
            )
            for USER_SEARCH in str(settings.AUTH_LDAP_SEARCH_OU).split("|")
        ]

        search = LDAPSearchUnion(*user_search_union)
        if search is None:
            raise ImproperlyConfigured(
                'AUTH_LDAP_USER_SEARCH must be an LDAPSearch instance.'
            )

        results = search.execute(self.connection, {'user': self._username})
        if results is not None and len(results) == 1:
            (user_dn, self._user_attrs) = next(iter(results))
        else:
            user_dn = None

        return user_dn 
Example #2
Source File: openldap2opendj.py    From community-edition-setup with MIT License 6 votes vote down vote up
def post_ldap_update(ldap_bind_dn, ldap_bind_pw):
    conn = ldap.initialize('ldaps://localhost:1636')
    conn.protocol_version = 3 
    conn.simple_bind_s(ldap_bind_dn, ldap_bind_pw)

    result = conn.search_s('ou=appliances,o=gluu',ldap.SCOPE_SUBTREE,'(oxIDPAuthentication=*)',['oxIDPAuthentication'])

    dn = result[0][0]
    oxIDPAuthentication = json.loads(result[0][1]['oxIDPAuthentication'][0])

    config = json.loads(oxIDPAuthentication['config'])

    if config['servers'][0]=='localhost:1636' and config['bindDN'].lower()=='cn=directory manager,o=gluu':
        config['bindDN'] = 'cn=Directory Manager'
        oxIDPAuthentication['config'] = json.dumps(config)
        oxIDPAuthentication = json.dumps(oxIDPAuthentication, indent=2)
        conn.modify_s(dn, [( ldap.MOD_REPLACE, 'oxIDPAuthentication',  oxIDPAuthentication)])

    result = conn.search_s('ou=appliances,o=gluu',ldap.SCOPE_SUBTREE,'(oxTrustConfCacheRefresh=*)',['oxTrustConfCacheRefresh'])

    dn = result[0][0]
    oxTrustConfCacheRefresh = json.loads(result[0][1]['oxTrustConfCacheRefresh'][0])
    oxTrustConfCacheRefresh['inumConfig']['bindDN'] = 'cn=Directory Manager'
    oxTrustConfCacheRefresh = json.dumps(oxTrustConfCacheRefresh, indent=2)
    conn.modify_s(dn, [( ldap.MOD_REPLACE, 'oxTrustConfCacheRefresh',  oxTrustConfCacheRefresh)]) 
Example #3
Source File: tests.py    From django-auth-ldap with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_or_group_query(self):
        self._init_settings(
            USER_DN_TEMPLATE="uid=%(user)s,ou=people,o=test",
            GROUP_SEARCH=LDAPSearch(
                "ou=query_groups,o=test",
                ldap.SCOPE_SUBTREE,
                "(objectClass=groupOfNames)",
            ),
            GROUP_TYPE=MemberDNGroupType(member_attr="member"),
        )
        alice = authenticate(username="alice", password="password")
        bob = authenticate(username="bob", password="password")

        query = LDAPGroupQuery("cn=alice_gon,ou=query_groups,o=test") | LDAPGroupQuery(
            "cn=bob_gon,ou=query_groups,o=test"
        )
        self.assertIs(query.resolve(alice.ldap_user), True)
        self.assertIs(query.resolve(bob.ldap_user), True) 
Example #4
Source File: tests.py    From django-auth-ldap with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_auth_signal_ldap_error(self):
        self._init_settings(
            BIND_DN="uid=bob,ou=people,o=test",
            BIND_PASSWORD="bogus",
            USER_SEARCH=LDAPSearch(
                "ou=people,o=test", ldap.SCOPE_SUBTREE, "(uid=%(user)s)"
            ),
        )

        def handle_ldap_error(sender, **kwargs):
            raise kwargs["exception"]

        with catch_signal(ldap_error) as handler:
            handler.side_effect = handle_ldap_error
            with self.assertRaises(ldap.LDAPError):
                authenticate(username="alice", password="password")
        handler.assert_called_once()
        _args, kwargs = handler.call_args
        self.assertEqual(kwargs["context"], "authenticate") 
Example #5
Source File: tests.py    From django-auth-ldap with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_nested_group_union(self):
        self._init_settings(
            USER_DN_TEMPLATE="uid=%(user)s,ou=people,o=test",
            GROUP_SEARCH=LDAPSearchUnion(
                LDAPSearch(
                    "ou=groups,o=test", ldap.SCOPE_SUBTREE, "(objectClass=groupOfNames)"
                ),
                LDAPSearch(
                    "ou=moregroups,o=test",
                    ldap.SCOPE_SUBTREE,
                    "(objectClass=groupOfNames)",
                ),
            ),
            GROUP_TYPE=NestedMemberDNGroupType(member_attr="member"),
            REQUIRE_GROUP="cn=other_gon,ou=moregroups,o=test",
        )

        alice = authenticate(username="alice", password="password")
        bob = authenticate(username="bob", password="password")

        self.assertIsNone(alice)
        self.assertIsNotNone(bob)
        self.assertEqual(bob.ldap_user.group_names, {"other_gon"}) 
Example #6
Source File: tests.py    From django-auth-ldap with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_group_union(self):
        self._init_settings(
            USER_DN_TEMPLATE="uid=%(user)s,ou=people,o=test",
            GROUP_SEARCH=LDAPSearchUnion(
                LDAPSearch(
                    "ou=groups,o=test", ldap.SCOPE_SUBTREE, "(objectClass=groupOfNames)"
                ),
                LDAPSearch(
                    "ou=moregroups,o=test",
                    ldap.SCOPE_SUBTREE,
                    "(objectClass=groupOfNames)",
                ),
            ),
            GROUP_TYPE=MemberDNGroupType(member_attr="member"),
            REQUIRE_GROUP="cn=other_gon,ou=moregroups,o=test",
        )

        alice = authenticate(username="alice", password="password")
        bob = authenticate(username="bob", password="password")

        self.assertIsNone(alice)
        self.assertIsNotNone(bob)
        self.assertEqual(bob.ldap_user.group_names, {"other_gon"}) 
Example #7
Source File: tests.py    From django-auth-ldap with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_require_group_as_group_query(self):
        query = LDAPGroupQuery("cn=alice_gon,ou=query_groups,o=test") & LDAPGroupQuery(
            "cn=mutual_gon,ou=query_groups,o=test"
        )
        self._init_settings(
            USER_DN_TEMPLATE="uid=%(user)s,ou=people,o=test",
            GROUP_SEARCH=LDAPSearch(
                "ou=query_groups,o=test",
                ldap.SCOPE_SUBTREE,
                "(objectClass=groupOfNames)",
            ),
            GROUP_TYPE=MemberDNGroupType(member_attr="member"),
            REQUIRE_GROUP=query,
        )

        alice = authenticate(username="alice", password="password")
        bob = authenticate(username="bob", password="password")

        self.assertIsNotNone(alice)
        self.assertIsNone(bob) 
Example #8
Source File: tests.py    From django-auth-ldap with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_nested_group_query(self):
        self._init_settings(
            USER_DN_TEMPLATE="uid=%(user)s,ou=people,o=test",
            GROUP_SEARCH=LDAPSearch(
                "ou=query_groups,o=test",
                ldap.SCOPE_SUBTREE,
                "(objectClass=groupOfNames)",
            ),
            GROUP_TYPE=MemberDNGroupType(member_attr="member"),
        )
        alice = authenticate(username="alice", password="password")
        bob = authenticate(username="bob", password="password")

        query = (
            LDAPGroupQuery("cn=alice_gon,ou=query_groups,o=test")
            & LDAPGroupQuery("cn=mutual_gon,ou=query_groups,o=test")
        ) | LDAPGroupQuery("cn=bob_gon,ou=query_groups,o=test")
        self.assertIs(query.resolve(alice.ldap_user), True)
        self.assertIs(query.resolve(bob.ldap_user), True) 
Example #9
Source File: tests.py    From django-auth-ldap with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_dn_group_membership(self):
        self._init_settings(
            USER_DN_TEMPLATE="uid=%(user)s,ou=people,o=test",
            GROUP_SEARCH=LDAPSearch("ou=groups,o=test", ldap.SCOPE_SUBTREE),
            GROUP_TYPE=MemberDNGroupType(member_attr="member"),
            USER_FLAGS_BY_GROUP={
                "is_active": LDAPGroupQuery("cn=active_gon,ou=groups,o=test"),
                "is_staff": [
                    "cn=empty_gon,ou=groups,o=test",
                    "cn=staff_gon,ou=groups,o=test",
                ],
                "is_superuser": "cn=superuser_gon,ou=groups,o=test",
            },
        )

        alice = authenticate(username="alice", password="password")
        bob = authenticate(username="bob", password="password")

        self.assertIs(alice.is_active, True)
        self.assertIs(alice.is_staff, True)
        self.assertIs(alice.is_superuser, True)
        self.assertIs(bob.is_active, False)
        self.assertIs(bob.is_staff, False)
        self.assertIs(bob.is_superuser, False) 
Example #10
Source File: tests.py    From django-auth-ldap with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_posix_membership(self):
        self._init_settings(
            USER_DN_TEMPLATE="uid=%(user)s,ou=people,o=test",
            GROUP_SEARCH=LDAPSearch("ou=groups,o=test", ldap.SCOPE_SUBTREE),
            GROUP_TYPE=PosixGroupType(),
            USER_FLAGS_BY_GROUP={
                "is_active": "cn=active_px,ou=groups,o=test",
                "is_staff": "cn=staff_px,ou=groups,o=test",
                "is_superuser": "cn=superuser_px,ou=groups,o=test",
            },
        )

        alice = authenticate(username="alice", password="password")
        bob = authenticate(username="bob", password="password")

        self.assertIs(alice.is_active, True)
        self.assertIs(alice.is_staff, True)
        self.assertIs(alice.is_superuser, True)
        self.assertIs(bob.is_active, False)
        self.assertIs(bob.is_staff, False)
        self.assertIs(bob.is_superuser, False) 
Example #11
Source File: tests.py    From django-auth-ldap with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_nested_dn_group_membership(self):
        self._init_settings(
            USER_DN_TEMPLATE="uid=%(user)s,ou=people,o=test",
            GROUP_SEARCH=LDAPSearch("ou=groups,o=test", ldap.SCOPE_SUBTREE),
            GROUP_TYPE=NestedMemberDNGroupType(member_attr="member"),
            USER_FLAGS_BY_GROUP={
                "is_active": "cn=parent_gon,ou=groups,o=test",
                "is_staff": "cn=parent_gon,ou=groups,o=test",
            },
        )
        alice = authenticate(username="alice", password="password")
        bob = authenticate(username="bob", password="password")

        self.assertIs(alice.is_active, True)
        self.assertIs(alice.is_staff, True)
        self.assertIs(bob.is_active, False)
        self.assertIs(bob.is_staff, False) 
Example #12
Source File: tests.py    From django-auth-ldap with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_group_permissions_ldap_error(self):
        self._init_settings(
            BIND_DN="uid=bob,ou=people,o=test",
            BIND_PASSWORD="bogus",
            USER_DN_TEMPLATE="uid=%(user)s,ou=people,o=test",
            GROUP_SEARCH=LDAPSearch("ou=groups,o=test", ldap.SCOPE_SUBTREE),
            GROUP_TYPE=MemberDNGroupType(member_attr="member"),
            FIND_GROUP_PERMS=True,
        )
        self._init_groups()

        backend = get_backend()
        alice = User.objects.create(username="alice")
        alice = backend.get_user(alice.pk)

        self.assertEqual(backend.get_group_permissions(alice), set()) 
Example #13
Source File: tests.py    From django-auth-ldap with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_empty_group_permissions(self):
        self._init_settings(
            USER_DN_TEMPLATE="uid=%(user)s,ou=people,o=test",
            GROUP_SEARCH=LDAPSearch("ou=groups,o=test", ldap.SCOPE_SUBTREE),
            GROUP_TYPE=MemberDNGroupType(member_attr="member"),
            FIND_GROUP_PERMS=True,
        )
        self._init_groups()

        backend = get_backend()
        bob = User.objects.create(username="bob")
        bob = backend.get_user(bob.pk)

        self.assertEqual(backend.get_group_permissions(bob), set())
        self.assertEqual(backend.get_all_permissions(bob), set())
        self.assertIs(backend.has_perm(bob, "auth.add_user"), False)
        self.assertIs(backend.has_module_perms(bob, "auth"), False) 
Example #14
Source File: tests.py    From django-auth-ldap with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_posix_group_permissions(self):
        self._init_settings(
            USER_DN_TEMPLATE="uid=%(user)s,ou=people,o=test",
            GROUP_SEARCH=LDAPSearch(
                "ou=groups,o=test", ldap.SCOPE_SUBTREE, "(objectClass=posixGroup)"
            ),
            GROUP_TYPE=PosixGroupType(),
            FIND_GROUP_PERMS=True,
        )
        self._init_groups()

        backend = get_backend()
        alice = User.objects.create(username="alice")
        alice = backend.get_user(alice.pk)

        self.assertEqual(
            backend.get_group_permissions(alice), {"auth.add_user", "auth.change_user"}
        )
        self.assertEqual(
            backend.get_all_permissions(alice), {"auth.add_user", "auth.change_user"}
        )
        self.assertIs(backend.has_perm(alice, "auth.add_user"), True)
        self.assertIs(backend.has_module_perms(alice, "auth"), True) 
Example #15
Source File: tests.py    From django-auth-ldap with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_posix_group_permissions_no_gid(self):
        self._init_settings(
            USER_DN_TEMPLATE="uid=%(user)s,ou=people,o=test",
            GROUP_SEARCH=LDAPSearch(
                "ou=groups,o=test", ldap.SCOPE_SUBTREE, "(objectClass=posixGroup)"
            ),
            GROUP_TYPE=PosixGroupType(),
            FIND_GROUP_PERMS=True,
        )
        self._init_groups()

        backend = get_backend()
        nonposix = User.objects.create(username="nonposix")
        nonposix = backend.get_user(nonposix.pk)

        self.assertEqual(
            backend.get_group_permissions(nonposix),
            {"auth.add_user", "auth.change_user"},
        )
        self.assertEqual(
            backend.get_all_permissions(nonposix), {"auth.add_user", "auth.change_user"}
        )
        self.assertIs(backend.has_perm(nonposix, "auth.add_user"), True)
        self.assertIs(backend.has_module_perms(nonposix, "auth"), True) 
Example #16
Source File: tests.py    From django-auth-ldap with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_group_mirroring(self):
        self._init_settings(
            USER_DN_TEMPLATE="uid=%(user)s,ou=people,o=test",
            GROUP_SEARCH=LDAPSearch(
                "ou=groups,o=test", ldap.SCOPE_SUBTREE, "(objectClass=posixGroup)"
            ),
            GROUP_TYPE=PosixGroupType(),
            MIRROR_GROUPS=True,
        )

        self.assertEqual(Group.objects.count(), 0)

        alice = authenticate(username="alice", password="password")

        self.assertEqual(Group.objects.count(), 3)
        self.assertEqual(set(alice.groups.all()), set(Group.objects.all())) 
Example #17
Source File: tests.py    From django-auth-ldap with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_group_mirroring_whitelist_update(self):
        self._init_settings(
            USER_DN_TEMPLATE="uid=%(user)s,ou=people,o=test",
            GROUP_SEARCH=LDAPSearch(
                "ou=mirror_groups,o=test",
                ldap.SCOPE_SUBTREE,
                "(objectClass=groupOfNames)",
            ),
            GROUP_TYPE=GroupOfNamesType(),
            MIRROR_GROUPS=["mirror1", "mirror2"],
        )

        backend = get_backend()
        groups = {}
        for name in ("mirror{}".format(i) for i in range(1, 5)):
            groups[name] = Group.objects.create(name=name)
        alice = backend.populate_user("alice")
        alice.groups.set([groups["mirror2"], groups["mirror4"]])

        alice = authenticate(username="alice", password="password")

        self.assertEqual(
            set(alice.groups.values_list("name", flat=True)), {"mirror1", "mirror4"}
        ) 
Example #18
Source File: tests.py    From django-auth-ldap with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_group_mirroring_whitelist_noop(self):
        self._init_settings(
            USER_DN_TEMPLATE="uid=%(user)s,ou=people,o=test",
            GROUP_SEARCH=LDAPSearch(
                "ou=mirror_groups,o=test",
                ldap.SCOPE_SUBTREE,
                "(objectClass=groupOfNames)",
            ),
            GROUP_TYPE=GroupOfNamesType(),
            MIRROR_GROUPS=["mirror1", "mirror2"],
        )

        backend = get_backend()
        groups = {}
        for name in ("mirror{}".format(i) for i in range(1, 5)):
            groups[name] = Group.objects.create(name=name)
        alice = backend.populate_user("alice")
        alice.groups.set([groups["mirror1"], groups["mirror3"]])

        alice = authenticate(username="alice", password="password")

        self.assertEqual(
            set(alice.groups.values_list("name", flat=True)), {"mirror1", "mirror3"}
        ) 
Example #19
Source File: tests.py    From django-auth-ldap with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_group_mirroring_blacklist_noop(self):
        self._init_settings(
            USER_DN_TEMPLATE="uid=%(user)s,ou=people,o=test",
            GROUP_SEARCH=LDAPSearch(
                "ou=mirror_groups,o=test",
                ldap.SCOPE_SUBTREE,
                "(objectClass=groupOfNames)",
            ),
            GROUP_TYPE=GroupOfNamesType(),
            MIRROR_GROUPS_EXCEPT=["mirror1", "mirror2"],
        )

        backend = get_backend()
        groups = {}
        for name in ("mirror{}".format(i) for i in range(1, 5)):
            groups[name] = Group.objects.create(name=name)
        alice = backend.populate_user("alice")
        alice.groups.set([groups["mirror1"], groups["mirror3"]])

        alice = authenticate(username="alice", password="password")

        self.assertEqual(
            set(alice.groups.values_list("name", flat=True)), {"mirror1", "mirror3"}
        ) 
Example #20
Source File: tests.py    From django-auth-ldap with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_authorize_external_users(self):
        self._init_settings(
            USER_DN_TEMPLATE="uid=%(user)s,ou=people,o=test",
            GROUP_SEARCH=LDAPSearch("ou=groups,o=test", ldap.SCOPE_SUBTREE),
            GROUP_TYPE=MemberDNGroupType(member_attr="member"),
            FIND_GROUP_PERMS=True,
            AUTHORIZE_ALL_USERS=True,
        )
        self._init_groups()

        backend = get_backend()
        alice = User.objects.create(username="alice")

        self.assertEqual(
            backend.get_group_permissions(alice), {"auth.add_user", "auth.change_user"}
        ) 
Example #21
Source File: tests.py    From django-auth-ldap with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_authorize_external_unknown(self):
        self._init_settings(
            USER_SEARCH=LDAPSearch(
                "ou=people,o=test", ldap.SCOPE_SUBTREE, "(uid=%(user)s)"
            ),
            GROUP_SEARCH=LDAPSearch("ou=groups,o=test", ldap.SCOPE_SUBTREE),
            GROUP_TYPE=MemberDNGroupType(member_attr="member"),
            FIND_GROUP_PERMS=True,
            AUTHORIZE_ALL_USERS=True,
        )
        self._init_groups()

        backend = get_backend()
        alice = User.objects.create(username="not-in-ldap")

        self.assertEqual(backend.get_group_permissions(alice), set()) 
Example #22
Source File: tests.py    From django-auth-ldap with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_pickle(self):
        self._init_settings(
            USER_DN_TEMPLATE="uid=%(user)s,ou=people,o=test",
            GROUP_SEARCH=LDAPSearch("ou=groups,o=test", ldap.SCOPE_SUBTREE),
            GROUP_TYPE=MemberDNGroupType(member_attr="member"),
            FIND_GROUP_PERMS=True,
        )
        self._init_groups()

        backend = get_backend()
        alice0 = authenticate(username="alice", password="password")

        pickled = pickle.dumps(alice0, pickle.HIGHEST_PROTOCOL)
        alice = pickle.loads(pickled)

        self.assertIsNotNone(alice)
        self.assertEqual(
            backend.get_group_permissions(alice), {"auth.add_user", "auth.change_user"}
        )
        self.assertEqual(
            backend.get_all_permissions(alice), {"auth.add_user", "auth.change_user"}
        )
        self.assertIs(backend.has_perm(alice, "auth.add_user"), True)
        self.assertIs(backend.has_module_perms(alice, "auth"), True) 
Example #23
Source File: tests.py    From django-auth-ldap with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_dn_cached(self, mock):
        self._init_settings(
            USER_SEARCH=LDAPSearch(
                "ou=people,o=test", ldap.SCOPE_SUBTREE, "(uid=%(user)s)"
            ),
            CACHE_TIMEOUT=60,
        )
        for _ in range(2):
            user = authenticate(username="alice", password="password")
            self.assertIsNotNone(user)
        # Should have executed only once.
        self.assertEqual(mock.call_count, 1)
        # DN is cached.
        self.assertEqual(
            cache.get("django_auth_ldap.user_dn.alice"), "uid=alice,ou=people,o=test"
        ) 
Example #24
Source File: connect_python_ldap.py    From Learning-Python-Networking-Second-Edition with MIT License 6 votes vote down vote up
def main():
	try:
		# Open a connection
		ldap_client = ldap.initialize(LDAP_SERVER)
		# Set LDAPv3 option
		ldap_client.set_option(ldap.OPT_PROTOCOL_VERSION,3)
		# Bind/authenticate with a user with appropriate rights
		ldap_client.simple_bind("admin",'Secret123')
		# Get user attributes defined in LDAP_ATTRS
		result = ldap_client.search_s(LDAP_BASE_DN,ldap.SCOPE_SUBTREE,LDAP_FILTER, LDAP_ATTRS)
		print(result)
	except ldap.INVALID_CREDENTIALS as exception:
		ldap_client.unbind()
		print('Wrong username or password. '+exception)
	except ldap.SERVER_DOWN as exception:
		print('LDAP server not available. '+exception) 
Example #25
Source File: __init__.py    From OctoPrint-LDAP with GNU Affero General Public License v3.0 6 votes vote down vote up
def ldap_search(self, ldap_filter, base=None, scope=ldap.SCOPE_SUBTREE):
        if not base:
            base = self.plugin_settings().get(["search_base"])
        try:
            client = self.get_ldap_client()
            if client is not None:
                self._logger.debug("Searching LDAP, base: %s and filter: %s" % (base, ldap_filter))
                result = client.search_s(base, scope, ldap_filter)
                client.unbind_s()
                if result:
                    dn, data = result[0]
                    """
                    # Dump LDAP search query results to logger
                    self._logger.debug("dn: %s" % dn)
                    for key, value in data.iteritems():
                        self._logger.debug("%s: %s" % (key, value))
                    """
                    return dict(dn=dn, data=data)
        except ldap.LDAPError as e:
            self._logger.error(json.dumps(e.message))
        return None 
Example #26
Source File: ldap_factory.py    From MCVirt with GNU General Public License v2.0 6 votes vote down vote up
def search_dn(self, username):
        """Determine a DN for a given username."""
        ldap_config = MCVirtConfig().get_config()['ldap']
        ldap_con = self.get_connection()

        try:
            res = ldap_con.search_s(str(ldap_config['base_dn']), ldap.SCOPE_SUBTREE,
                                    self.get_user_filter(username),
                                    [str(ldap_config['username_attribute'])])

        except Exception:
            raise UnknownLdapError(('An LDAP search error occurred. Please read the MCVirt'
                                    ' logs for more information'))
        if len(res):
            return res[0][0]
        else:
            raise UserDoesNotExistException('User not returned by LDAP search') 
Example #27
Source File: ldap_factory.py    From MCVirt with GNU General Public License v2.0 6 votes vote down vote up
def get_all_usernames(self):
        """Return all users in the searchable LDAP directory."""
        if not LdapFactory.is_enabled():
            return []

        ldap_config = MCVirtConfig().get_config()['ldap']
        ldap_con = self.get_connection()

        try:
            res = ldap_con.search_s(ldap_config['base_dn'], ldap.SCOPE_SUBTREE,
                                    self.get_user_filter(),
                                    [str(ldap_config['username_attribute'])])
        except Exception:
            raise UnknownLdapError(('An LDAP search error occurred. Please read the MCVirt'
                                    ' logs for more information'))
        return [user_obj[1][ldap_config['username_attribute']][0] for user_obj in res] 
Example #28
Source File: tests.py    From django-auth-ldap with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_dn_group_permissions(self):
        self._init_settings(
            USER_DN_TEMPLATE="uid=%(user)s,ou=people,o=test",
            GROUP_SEARCH=LDAPSearch("ou=groups,o=test", ldap.SCOPE_SUBTREE),
            GROUP_TYPE=MemberDNGroupType(member_attr="member"),
            FIND_GROUP_PERMS=True,
        )
        self._init_groups()

        backend = get_backend()
        alice = User.objects.create(username="alice")
        alice = backend.get_user(alice.pk)

        self.assertEqual(
            backend.get_group_permissions(alice), {"auth.add_user", "auth.change_user"}
        )
        self.assertEqual(
            backend.get_all_permissions(alice), {"auth.add_user", "auth.change_user"}
        )
        self.assertIs(backend.has_perm(alice, "auth.add_user"), True)
        self.assertIs(backend.has_module_perms(alice, "auth"), True) 
Example #29
Source File: windapsearch.py    From windapsearch with GNU General Public License v3.0 5 votes vote down vote up
def getAdminObjects(self, attrs=''):
        if not attrs:
            attrs = ['dn']
        objectFilter = 'adminCount=1'
        base_dn = self.domainBase
        try:
            rawAdminResults = self.do_ldap_query(base_dn, ldap.SCOPE_SUBTREE, objectFilter, attrs)
        except ldap.LDAPError as e:
            print("[!] Error retrieving admin objects")
            print("[!] {}".format(e))
            sys.exit(1)
        return self.get_search_results(rawAdminResults), attrs 
Example #30
Source File: windapsearch.py    From windapsearch with GNU General Public License v3.0 5 votes vote down vote up
def getUnconstrainedComputers(self, attrs=''):
        if not attrs:
            attrs = ['dn', 'dNSHostName']
        objectFilter = "(&(objectCategory=computer)(objectClass=computer)(userAccountControl:1.2.840.113556.1.4.803:=524288))"
        base_dn = self.domainBase
        try:
            rawUnconstrainedComputers = self.do_ldap_query(base_dn, ldap.SCOPE_SUBTREE, objectFilter, attrs)
        except ldap.LDAPError as e:
            print("[!] Error retrieving unconstrained computers")
            print("[!] {}".format(e))
            sys.exit(1)
        return self.get_search_results(rawUnconstrainedComputers), attrs