Last active
February 8, 2024 16:24
-
-
Save JosephRedfern/c405d1dcd36fca619b3b0f37defd5962 to your computer and use it in GitHub Desktop.
Sync LDAP users with Django users.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.core.management.base import BaseCommand, CommandError | |
from django.contrib.auth.models import User | |
import ldap | |
class Command(BaseCommand): | |
help = 'Syncs LDAP users with Django DB' | |
def handle(self, *args, **options): | |
l = ldap.initialize(settings.AUTH_LDAP_SERVER_URI) | |
results = l.search_s(settings.USERS_DN, ldap.SCOPE_SUBTREE, "(employeeType=*Research Student*)") | |
total_created = 0 | |
total = 0 | |
for a,r in results: | |
username = r['uid'][0].decode('utf-8') # returns bytes by default so we need to decode to string. | |
first_name = r['givenName'][0].decode('utf-8') | |
last_name = r['sn'][0].decode('utf-8') | |
email = r['mail'][0].decode('utf-8') | |
# Update the user -- this allows for name changes etc, using username as the key. | |
user, created = User.objects.update_or_create(username=username, defaults={'email': email, 'first_name': first_name, 'last_name': last_name}) | |
total += 1 | |
if created: | |
# Set an unusable password -- django-auth-ldap handles this, anyway. | |
user.set_unusable_password() | |
user.save() | |
total_created += 1 | |
self.stdout.write(self.style.SUCCESS('Found {} user(s), {} new.'.format(total, total_created))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment