Applying Constraints for System Accounts

The account module provides a role-based access control mechanism. You can set constraints for system accounts to restrict their behaviors.

Constraints

For details about the predefined account constraints, see Constraints.

Before You Start

  1. Request the ohos.permission.MANAGE_LOCAL_ACCOUNTS permission. For details, see Requesting Permissions for system_basic Applications.

  2. Import the osAccount module.

    import account_osAccount from '@ohos.account.osAccount';
    
  3. Obtain an AccountManager instance.

    let accountManager = account_osAccount.getAccountManager();
    

Setting Constraints for a System Account

The user can set constraints to restrict the system account behaviors. For example, the user can enable mobile guardian for children to prevent the kids to use Wi-Fi or install apps.

Procedure

  1. Specify the system account ID and the constraints.

    let localId: number = 100;
    let constraint: string[] = [ 'constraint.wifi.set' ];
    
  2. Use setOsAccountConstraints to enable the constraints for the system account.

    try {
      let accountManager.setOsAccountConstraints(localId, [constraint], true);
      console.log('setOsAccountConstraints successfully');
    } catch (err) {
      console.log('setOsAccountConstraints failed, error: ' + JSON.stringify(err));
    }
    

Checking Whether a Constraint Can be Enabled for a System Account

Before a constraint is enabled for a system account, the application needs to check whether the constraint can be enabled. You can use isOsAccountConstraintEnabled to implement this operation.

Procedure

  1. Specifies the system account ID and constraint.

    let localId: number = 100;
    let constraint: string = 'constraint.wifi.set';
    
  2. Use isOsAccountConstraintEnabled to check whether the constraint can be enabled for the system account.

    let isEnabled: boolean = await accountManager.isOsAccountConstraintEnabled(localId, constraint);
    if (isEnabled) {
      // Your business logic
    }