We use cookies to improve your experience.
By your continued use of this site you accept such use.
For more details please see our privacy policy and cookies policy.

Script Repository

Check whether email and username are unique

February 23, 2021 Views: 3201

The script checks whether the email address and username specified for a new user are unique. If either the username or the email address are not unique, new user creation will be cancelled. To use the script with Adaxes, create a business rule triggered before creating a user. For details, see Validate/Modify User Input Using a Script.

Edit Remove
PowerShell
# Build search filter
$filter = "(&(sAMAccountType=805306368)(|(sAMAccountName=%username%)"
if (-not([System.String]::IsNullOrEmpty("%mail%")))
{
    $filter += "(mail=%mail%)"
}
$filter += "))"

# Search for users with the username or email address specified
$searcher = $Context.BindToObject("Adaxes://rootDSE")
$searcher.SearchFilter = $filter
$searcher.SearchScope = "ADS_SCOPE_SUBTREE"
$searcher.PageSize = 500
$searcher.ReferralChasing = "ADS_CHASE_REFERRALS_NEVER"
$searcher.VirtualRoot = $True
$searcher.SizeLimit = 1

try
{
    $searchResultIterator = $searcher.ExecuteSearch()
    $searchResults = $searchResultIterator.FetchAll()
    
    if ($searchResults.Length -ne 0)
    {
        $Context.Cancel("A user with the same username or email address already exists")
        return
    }
}
finally
{
    # Release resources
    $searchResultIterator.Dispose()
}
Comments 2
avatar
Ray Bilyk Apr 02, 2021
Is there a way to get an email if the new user creation is cancelled due to lack of uniqueness?
avatar
Support Apr 02, 2021
Hello Ray,

Yes, it is possible. You can use the $Context.SendMail method right after the following line in the script:

$Context.Cancel("A user with the same username or email address already exists")

Should you have any issues updating the script to meet your needs, please, describe the desired behavior in all the possible details with live examples.
Leave a comment
Loading...

Got questions?

Support Questions & Answers