username check added for ldap

This commit is contained in:
ahmadbilalkhalid 2019-12-13 15:05:27 +05:00
parent 37a3d21e0c
commit c96aff16af
2 changed files with 19 additions and 15 deletions

View file

@ -1 +1 @@
10173 10178

View file

@ -1,4 +1,5 @@
import logging import logging
import random
from datetime import datetime from datetime import datetime
from django.conf import settings from django.conf import settings
@ -77,24 +78,27 @@ def get_first_and_last_name(full_name):
def assign_username(user): def assign_username(user):
if not user.username: if not user.username:
ldap_manager = LdapManager()
# Try to come up with a username
first_name, last_name = get_first_and_last_name(user.name) first_name, last_name = get_first_and_last_name(user.name)
user.username = first_name.lower() + last_name.lower() user.username = first_name.lower() + last_name.lower()
user.username = "".join(user.username.split()) user.username = "".join(user.username.split())
try:
user.save() exist = True
except IntegrityError: while exist:
try: # Check if it exists
user.username = user.username + str(user.id) exist, entries = ldap_manager.check_user_exists(user.username)
user.save() if exist:
except IntegrityError: # If username exists in ldap, come up with a new user name and check it again
while True: user.username = user.username + str(random.randint(0, 2 ** 50))
else:
# If username does not exists in ldap, try to save it in database
try:
user.save()
except IntegrityError:
# If username exists in database then come up with a new username
user.username = user.username + str(random.randint(0, 2 ** 50)) user.username = user.username + str(random.randint(0, 2 ** 50))
try:
user.save()
except IntegrityError:
continue
else:
break
class CustomUser(AbstractBaseUser, PermissionsMixin): class CustomUser(AbstractBaseUser, PermissionsMixin):