def create_or_update_safe(username, password, uuid, date, registering_phone_id, domain, user_data, **kwargs): # check for uuid conflicts, if one exists, respond with the already-created user conflicting_user = CommCareUser.get_by_user_id(uuid) # we need to check for username conflicts, other issues # and make sure we send the appropriate conflict response to the phone try: username = normalize_username(username, domain) except ValidationError: raise Exception("Username (%s) is invalid: valid characters include [a-z], " "[0-9], period, underscore, and single quote" % username) if conflicting_user: # try to update. If there are username conflicts, we have to resolve them if conflicting_user.domain != domain: raise Exception("Found a conflicting user in another domain. This is not allowed!") saved = False to_append = 2 prefix, suffix = username.split("@") while not saved and to_append < MAX_DUPLICATE_USERS: try: conflicting_user.change_username(username) conflicting_user.password = password conflicting_user.date = date conflicting_user.device_id = registering_phone_id conflicting_user.user_data = user_data conflicting_user.save() saved = True except CouchUser.Inconsistent: username = "******" % { "pref": prefix, "count": to_append, "suff": suffix} to_append = to_append + 1 if not saved: raise Exception("There are over 1,000,000 users with that base name in your domain. REALLY?!? REALLY?!?!") return (conflicting_user, False) try: User.objects.get(username=username) except User.DoesNotExist: # Desired outcome pass else: # Come up with a suitable username prefix, suffix = username.split("@") username = get_unique_value(User.objects, "username", prefix, sep="", suffix="@%s" % suffix) couch_user = cls.create(domain, username, password, uuid=uuid, device_id=registering_phone_id, date=date, user_data=user_data ) return (couch_user, True)
def new_django_user_object(chw): """From a CHW object, automatically build a django user""" user = User() user.username = get_unique_value(User.objects, "username", chw.username, "") user.set_password(chw.password) user.first_name = chw.first_name user.last_name = chw.last_name user.email = "" user.is_staff = False # Can't log in to admin site user.is_active = True # Activated upon receipt of confirmation user.is_superuser = False # Certainly not user.last_login = datetime(1970,1,1) user.date_joined = datetime.utcnow() return user