getKeyFromUserIfRequired function

Future<void> getKeyFromUserIfRequired(
  1. BuildContext context,
  2. Widget child
)

Ask for the security key from the user if the security key is not available or cannot be verfied using the verification key stored in PODs.

Implementation

Future<void> getKeyFromUserIfRequired(
  BuildContext context,
  Widget child,
) async {
  if (await KeyManager.hasSecurityKey()) {
    return;
  } else {
    final verificationKey = await KeyManager.getVerificationKey();
    // Get the webId to display in the security key prompt.

    final webId = await getWebId();

    const inputKey = 'security_key';
    final inputField = (
      fieldKey: inputKey,
      fieldLabel: 'Security Key',
      validateFunc: (key) {
        assert(key != null);
        return verifySecurityKey(key as String, verificationKey)
            ? null
            : 'Incorrect Security Key';
      }
    );

    // Use the unified SecurityKeyUI widget with the appropriate configuration.

    final securityKeyInput = SecurityKeyUI(
      webId: webId,
      title: 'Security Key',
      message: SecurityStrings.securityKeyPrompt,
      inputFields: [inputField],
      formKey: GlobalKey<FormBuilderState>(),
      submitFunc: (formDataMap) async {
        await KeyManager.setSecurityKey(formDataMap[inputKey].toString());
        debugPrint('Security key saved');
        if (context.mounted) Navigator.pop(context);
      },
      child: child,
    );

    if (context.mounted) {
      await Navigator.push(
        context,
        MaterialPageRoute(builder: (context) => securityKeyInput),
      );
    }
  }
}