Newer Version Available

This content describes an older version of this product. View Latest

UserManagement Class

Contains methods to manage end users, for example, to register verification methods or handle requests for Salesforce to forget them.

Namespace

System

Usage

Use the register and deregister methods to for your users to register and deregister identity verification methods. Use the obfuscateUser method to scramble user object data on a user’s request. Use the formatPhoneNumber method to ensure the phone number properly formatted.

This class is introduced in API version 43.0. It isn't available in earlier versions.

UserManagement Methods

The following are methods for UserManagement.

clone()

Makes a duplicate copy of the System.UserManagement object.

Signature

public Object clone()

Return Value

Type: User Management

deregisterVerificationMethod(userId, method)

Deregisters an identity verification method. Use this method to allow users to delete an existing verification method.

Signature

public static void deregisterVerificationMethod(Id userId, Auth.VerificationMethod method)

Parameters

userId
Type: Id
User ID of the user deregistering the verification method.
method
Type: Auth.VerificationMethod
Verification method used to verify the identity of the user.

Return Value

Type: void

Usage

Use this method to deregister an existing identity verification method. For example, your users can deregister a phone number when their phone number changes. While only end users can register an identity verification method, you and your users can deregister one. Keep this behavior in mind when you implement a custom registration page.

This method is introduced in API version 43.0. It isn't available in earlier versions.

formatPhoneNumber(countryCode, phoneNumber)

Formats a mobile phone number for a user. Call this method to ensure that the phone number is formatted properly before updating a user’s mobile phone number.

Signature

global static String formatPhoneNumber(String countryCode, String phoneNumber)

Parameters

countryCode
Type: String
A valid country code.
phoneNumber
Type: String
A mobile number that contains from 3 through 49 numeric characters, without the country code. For example, (415) 555-1234.

Return Value

Type: String

Returns a user’s mobile phone number in the proper format.

Usage

Use this method to ensure a user’s mobile phone number is formatted as required by Salesforce. Then use the method’s return value to update the mobile field of the user’s record. This mobile number is used for SMS-based identity confirmation. For example, mobile phone numbers are stored along with other identity verification methods in Auth.VerificationMethod enum. This method is introduced in API version 43.0. It isn't available in earlier versions.

Here are some acceptable ways that users can enter their mobile number:

  • +1, (415) 555-1234 (with plus signs, parentheses, and dashes)
  • 1, 4155551234 (only numbers, no symbols)
  • 1 , 415-555-1234 (extra spaces)

Now, consider the following examples.

  • Correct examples:
    • formatPhoneNumber('1', '4155551234');
    • formatPhoneNumber('+1','(415) 555-1234');
    • formatPhoneNumber('1', '415-555-1234');
  • Incorrect example, because the country code and mobile number aren’t separated:
    • formatPhoneNumber(null, '+1 415-555-1234');
  • Example that doesn’t generate an error, but likely won’t work as intended:
    • formatPhoneNumber('+1', '+1 (415) 555-1234');

Format Phone Number Code Example

Here's a code example that uses the formatPhoneNumber method. It gets the mobile number from the user and converts it to the format required by Salesforce. Then it updates the user’s record with the formatted mobile number.

1global with sharing class PhoneRegistrationController {
2    //Input variables 
3    global String countryCode {get; set;}
4    global String phoneNumber {get; set;}
5
6    global String addPhoneNumber() 
7    {
8        if(countryCode == null) return 'Country code is required';
9        if(phoneNumber == null) return 'Phone number is required';
10        
11        String userId = UserInfo.getUserId();
12        User u = [SELECT Id FROM User WHERE Id=:userId LIMIT 1];
13        String formatNum = System.UserManagement.formatPhoneNumber(countryCode, phoneNumber);        
14        u.MobilePhone = formatNum;        
15        update u;        
16        return null;        
17    }
18        
19}

As long as the country code and phone number are separated, formatPhoneNumber returns a value in the proper format.

initSelfRegistration(method, user)

Use this method to invoke a verification challenge when creating your own Verify page for community self-registration.

Signature

public static String initSelfRegistration(Auth.VerificationMethod method, User user)

Parameters

method
Type: VerificationMethod Enum
Verification method used to verify the user’s identity, which can be EMAIL or SMS.
user
Type: User
User object to insert after successful registration.

Return Value

Type: String

Usage

By default, when users sign up for your community with an email address or phone number, Salesforce sends them a verification code and generates the Verify page for users to confirm their identity. You can replace the default Salesforce Verify page with your own Visualforce page. Then, you invoke the verification process with the initSelfRegistration and verifySelfRegistraion methods.

First, call initSelfRegistration, to initiate an authentication challenge. Include a user object to be inserted on successful registration. It returns the unique identifier for the registration attempt. Then call verifySelfRegistration to complete the verification.

Example

For an example, see VerificationResult Class.

obfuscateUser(userId, username)

Scrambles users’ data on their request when they no longer want their personal data recognized in Salesforce. When you invoke the method for the user, the data becomes anonymous, and you can never recover it. Use this method to set the username to a specific value after it’s scrambled.

Signature

public static void obfuscateUser(Id userId, String username)

Parameters

userId
Type: Id
ID of the user whose data this method scrambles.
username
Type: String
The username after the user’s data is scrambled. Sets the value of the scrambled username to a specific string.

Return Value

Type: void

Usage

This method is introduced in API version 43.0. It isn't available in earlier versions.

You can use the obfuscateUser method to protect the personal information of your org’s users. When invoked, Salesforce permanently scrambles the user’s object data and replaces it with random character strings. The user’s detail page exists, but the fields contain meaningless strings of characters. Salesforce merely obfuscates (scrambles) personal data because you can't delete a user in Salesforce; you can only disable or deactivate a user. In other words, the user record remains in the database and this method performs a soft delete.

Take care when using this method. The users’ data becomes anonymous and can never be recovered.

Note

Considerations

  • This method requires that the org’s User Management setting, Scramble Specific Users' Data, is enabled from Setup.
  • This method affects the standard fields of the user object—excluding a few fields such as the user ID, timezone, locale, and profile.
  • It is recommended that you note the user's ID and other attributes for post processing, such as the email address, if you want to send the user a confirmation.
  • This method changes only the user object. The association between the user and other objects is removed, but no other objects are changed. For example, contact, ThirdPartyAccountLink (TPAL), and user password authentication (UPA) objects remain unchanged.

Assure your admins that invoking this method doesn’t trigger an email change notification.

Note

This method is part of our effort to protect users’ personal data and privacy. For more information on what you can do to actively protect user data, see Data Protection and Privacy in Salesforce Help.

obfuscateUser(userId)

Scrambles users’ data on their request when they no longer want their personal data recognized in Salesforce. When you invoke the method for the user, the data becomes anonymous, and you can never recover it.

Signature

public static void obfuscateUser(Id userId)

Parameters

userId
Type: Id
ID of the user whose data this method scrambles.

Return Value

Type: void

Usage

This method is introduced in API version 43.0. It isn't available in earlier versions.

You can use the obfuscateUser method to protect the personal information of your org’s users. When invoked, Salesforce permanently scrambles the user’s object data and replaces it with random character strings. The user’s detail page exists, but the fields contain meaningless strings of characters. Salesforce merely obfuscates (scrambles) personal data because you can't delete a user in Salesforce; you can only disable or deactivate a user. In other words, the user record remains in the database and this method performs a soft delete.

Take care when using this method. The users’ data becomes anonymous and can never be recovered.

Note

Considerations

  • This method requires that the org’s User Management setting, Scramble Specific Users' Data, is enabled from Setup.
  • This method affects the standard fields of the user object—excluding a few fields such as the user ID, timezone, locale, and profile.
  • It is recommended that you note the user's ID and other attributes for post processing, such as the email address, if you want to send the user a confirmation.
  • This method changes only the user object. The association between the user and other objects is removed, but no other objects are changed. For example, contact, ThirdPartyAccountLink (TPAL), and user password authentication (UPA) objects remain unchanged.

Assure your admins that invoking this method doesn’t trigger an email change notification.

Note

This method is part of our effort to protect users’ personal data and privacy. For more information on what you can do to actively protect user data, see Data Protection and Privacy in Salesforce Help.

ObfuscateUser Code Example

1public class UserManagementController{
2    public List <User> users {getset;}
3    
4    public UserManagementController()
5    {
6        Profile p = [select id from profile where name = 'Customer Community User'];
7        
8        users = [select usernameid from User where profileId=:p.id AND isactive=true];
9    }
10
11    //Use method with extreme caution. Data can't be recovered.   
12    @InvocableMethod(label='User Management' description='Obfuscate User data and more')
13    static public void obfuscate(List<User> users)
14    {
15        String uid = ApexPages.currentPage().getParameters().get('uid');
16        
17        if(uid == null)
18            return;
19        
20        User u = [select contactId from user where id=:uid];
21            
22        System.UserManagement.obfuscateUser(uid);
23        
24        if(u.contactId != null)
25        {
26            List <Contact> contacts = [select id from Contact where id=:u.contactId LIMIT 1];
27            if (contacts == null || contacts.isEmpty() == true)
28            return;
29                
30            delete contacts;
31        }
32    }
33}

registerVerificationMethod(method, startUrl)

Registers an identity verification method. Verification methods include a time-based one-time password, email or text one-time password, Salesforce Authenticator, or U2F. End users register their verification methods.

Signature

public static System.PageReference registerVerificationMethod(Auth.VerificationMethod method, String startUrl)

Parameters

method
Type: Auth.VerificationMethod
Verification method used to verify the identity of the user.
startUrl
Type: String
Path to the page that users see after they log in.

Return Value

Type:System.PageReference

Usage

Use this method to enable users to complete identity verification, such as 2FA, or to log in to their community without a password. Users register these methods to verify their identity when logging in. You create a custom registration page when implementing mobile-friendly passwordless logins. See passwordlessLogin.

The PageReference returned by registerVerificationMethod redirects the user to the Salesforce verification page. If the user enters the correct code, the user is redirected to the community page specified by the start URL. For example:

1PageReference pr = System.UserManagement.registerVerificationMethod(Auth.VerificationMethod.TOTP,startUrl);
2PageReference p =  System.UserManagement.deregisterVerificationMethod(userId,Auth.VerificationMethod.SALESFORCE_AUTHENTICATOR);

This method is introduced in API version 43.0. It isn’t available in earlier versions.

As a security measure, when users add or update mobile numbers in Advanced User Details, they must log in again to verify their identity. As a result, unsaved changes in the app are lost. To disable this security measure, contact Salesforce Support.

Note

sendAsyncEmailConfirmation(userId, emailTemplateId, networkId, startUrl)

Send an email message to a user’s email address for verification. The message contains a verification link (URL) that the user clicks to verify the email address later on. You can send email verifications in bulk.

Signature

public static Boolean sendAsyncEmailConfirmation(String userId, String emailTemplateId, String networkId, String startUrl)

Parameters

userId
Type: String
ID of the user to receive the email confirmation.
emailTemplateId
Type: String
ID of the email template in which the verification link is defined.
networkId
Type: String
ID of the community.
startUrl
Type: String
The user is redirected to this page after verification, with a success or error message as the parameter. If null, the user is redirected to the login page.

Return Value

Type: Boolean

Indicates whether sending the email message succeeded or failed.

Usage

Sending an async email message is good practice to ensure that users are registered with a valid email address that they truly own. To determine which users receive an email with the verification link, check whether the User Verified Email field in the User detail page is set to true. You can also get this information from the TwoFactorMethodsInfo API.

Send async email verification to external users to verify their email address. External users must verify their email address before they can log in with email OTP (passwordless login).

The error code and description are passed as query parameters so that you can process any errors when building a custom landing page.

Example

1System.UserManagement.sendAsyncEmailConfirmation('005RM000001a0Ox', 
2'00XRM000000hxnG','0DBRM000000015i', '/s/contactsupport');

verifySelfRegistration(method, identifier, code, startUrl)

Use this method to complete a verification challenge when creating your own Verify page for community self-registration. If the person who is attempting to register enters the verification code successfully, the user is created and logged in.

Signature

public static Auth.VerificationResult verifySelfRegistration(Auth.VerificationMethod method, String identifier, String code, String startUrl)

Parameters

method
Type: VerificationMethod Enum
The verification method.
identifier
Type: String
The unique identifier received from the initSelfRegistration method.
code
Type: String
Verification code received from verification method, for example, EMAIL or SMS.
startUrl
Type: String
The page that the user is directed to after successful self-registration.

Return Value

Type: Auth.VerificationResult

Usage

By default, when users sign up for your community with an email address or phone number, Salesforce sends them a verification code and generates the Verify page for users to confirm their identity. You can replace the default Salesforce Verify page with your own Visualforce page. Then, you invoke the verification process with the initSelfRegistration and verifySelfRegistraion methods.

verifySelfRegistration completes the verification, and if successful, the user is created and logged in. verifySelfRegistration returns the verification result, which contains the verification status and session ID if the user is created. If the verification method is SMS, the user object must contain a properly formatted mobile number, which is country code, space, and then phone number. For example, +1 1234567890. See System.UserManagement.formatPhoneNumber.

Example

For an example, see VerificationResult Class.