management: Move `query_ldap` function to `zproject/backends.py`.

This will make it simpler to organize and unit-test all of our
authentication backend code.
This commit is contained in:
Harshit Bansal 2019-03-09 06:52:14 +00:00 committed by Tim Abbott
parent 873aca4a82
commit b519e6594e
2 changed files with 20 additions and 20 deletions

View File

@ -2,28 +2,9 @@
from argparse import ArgumentParser
from typing import Any
from django.conf import settings
from django.contrib.auth import get_backends
from django.core.management.base import BaseCommand
from django_auth_ldap.backend import LDAPBackend, _LDAPUser
# Quick tool to test whether you're correctly authenticating to LDAP
def query_ldap(**options: str) -> None:
email = options['email']
for backend in get_backends():
if isinstance(backend, LDAPBackend):
ldap_attrs = _LDAPUser(backend, backend.django_to_ldap_username(email)).attrs
if ldap_attrs is None:
print("No such user found")
else:
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)"
print("%s: %s" % (django_field, value))
if settings.LDAP_EMAIL_ATTR is not None:
print("%s: %s" % ('email', ldap_attrs[settings.LDAP_EMAIL_ATTR]))
from zproject.backends import query_ldap
class Command(BaseCommand):
def add_arguments(self, parser: ArgumentParser) -> None:

View File

@ -17,6 +17,7 @@ from typing import Any, Dict, List, Optional, Set, Tuple, Union
from django_auth_ldap.backend import LDAPBackend, _LDAPUser
import django.contrib.auth
from django.contrib.auth import get_backends
from django.contrib.auth.backends import RemoteUserBackend
from django.conf import settings
from django.core.exceptions import ValidationError
@ -590,6 +591,24 @@ def sync_user_from_ldap(user_profile: UserProfile) -> bool:
return False
return True
# Quick tool to test whether you're correctly authenticating to LDAP
def query_ldap(**options: str) -> None:
email = options['email']
for backend in get_backends():
if isinstance(backend, LDAPBackend):
ldap_attrs = _LDAPUser(backend, backend.django_to_ldap_username(email)).attrs
if ldap_attrs is None:
print("No such user found")
else:
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)"
print("%s: %s" % (django_field, value))
if settings.LDAP_EMAIL_ATTR is not None:
print("%s: %s" % ('email', ldap_attrs[settings.LDAP_EMAIL_ATTR]))
class DevAuthBackend(ZulipAuthMixin):
"""Allow logging in as any user without a password. This is used for
convenience when developing Zulip, and is disabled in production."""