Check if an user is already present with same email id

I’m trying add a new user but before adding I need to check if an user is already present with the same email address. How can this be achieved?
eg:

userToGet = system.user.getNewUser("AcmeWest", "mTrejo")
  
# Add some contact info
contactInfo = {"email":"mTrejo@acmewest.com","sms": "5551234"}
userToGet.addContactInfo(contactInfo)
userToGet.set("password", "thisIsMyPassword")
 
# Adds a user to the the AcmeWest usersource.
system.user.addUser("AcmeWest", userToGet)

I need to check if there already exists an user with email:"mTrejo@acmewest.com"

You would need to iterate through the existing users, and look at each contactInfo:

# Get users from the usersouce
users = system.user.getUsers('AcmeWest')

emailExists = False

for user in users:
	# Get contact info for the user
	contactInfo = user.getContactInfo()
	for item in contactInfo:
		# Check if a matching email exists
		if item.getContactType() == 'email' and  item.getValue() == 'mTrejo@acmewest.com':
			emailExists = True
	# Break out of the loop if we find a match
	if emailExists:
		break
		
if emailExists:
	uh_oh()
else:
	do_some_stuff()
1 Like

If I'm trying to edit an user can I give a condition so that it does check the email of the user I'm currently editing?

For that I would need to access the 'username' in user

Since you already have the user, you can use system.user.getUser() to get a single user.

user = system.user.getUser('AcmeWest', 'mTrejo')

emailExists = False

contactInfo = user.getContactInfo()
for item in contactInfo:
	# Check if a matching email exists
	if item.getContactType() == 'email' and  item.getValue() == 'mTrejo@acmewest.com':
		emailExists = True
		break
			
if emailExists:
	uh_oh()
else:
	do_some_stuff()

Yes. That's the method :innocent:

We can use user.get("username") to get the userName