How to auto generate a password for new users via the registration web part
This article will explain how to auto generate and email a password for new users according to your site’s password policy, using the Registration Form web part. Since we are going to leverage the existing functionality of the Registration Form web part, it is recommended to create a copy of this web part and register it as a custom web part. Web parts can be registered in Site Manager -> Development -> Web parts -> New web part.
The default Registration web part can be found in the following location: ~\CMSWebParts\Membership\Registration\RegistrationForm.ascx(.cs). The
CMS.SiteProvider.UserInfoProvider.GenerateNewPassword method will generate a new password based on the password policy settings in Site Manager -> Settings -> Security & Membership -> Passwords -> Password policy settings.
Opening the RegistrationForm.ascx.cs file, you should see the default code below around line 733:
// Set password
UserInfoProvider.SetPassword(ui, passStrength.Text);
We want to change this and add the
GenerateNewPassword method which takes the siteName as its only parameter. You can either hardcode the site name, or use
CMSContext.CurrentSite.SiteName, which resolves the current site’s name.
The modified code will be:
// Set password – modified sNewPassword string returns generated password
string sNewPassword = UserInfoProvider.GenerateNewPassword(CMSContext.CurrentSite.SiteName);
UserInfoProvider.SetPassword(ui, sNewPassword);
Now that we have generated the password, we need to email it to the user, to ensure they can login to the site. Since the Registration form web part already contains this functionality, we only need to replace the current password text with the newly generated password. If you look around line 802, you should see the following default line:
replacements[2, 1] = passStrength.Text;
We want to replace this with our password string from line 733:
replacements[2, 1] = sNewPassword;
Since the default password fields contain validation checks, you will need to remove or comment out these checks in both the RegistrationForm.ascx and .cs files for the
lblPassword,
passStrength,
lblConfirmPassword, and
rfvConfirmPassword fields. This will also remove the default Password and Password confirmation textboxes from the form.
RegistrationForm.ascx lines – 45, 48 53, and 59.
RegistrationForm.ascx.cs lines – 103, 120, 447, 460, 461, 469, 475, 476, 489, 504, 505, 509, 557 – 585, and 735.
Your new form should look like:
To ensure an email is sent once the user registers, we need to go to the web part properties and enable the Send welcome e-mail option.
And the registration email with auto generated password based on the password policy settings in Site Manager -> Settings -> Security & Membership -> Passwords -> Password policy settings.
-eh-
See also: Password Management
Kentico CMS ApiApplies to: Kentico CMS Version 7.x