DEV Community

Cover image for Authorization persistence
liu yang
liu yang

Posted on • Edited on

Authorization persistence

Managing File Permissions in HarmonyOS: A Comprehensive Guide

Introduction

In HarmonyOS, managing file permissions is crucial for ensuring secure and efficient data access across devices. This guide provides detailed examples and explanations for persisting and revoking file permissions using the fileShare module. By following these steps, you can ensure that your application handles file permissions correctly, enhancing both security and user experience.

Persisting File Permissions

Persisting file permissions allows your application to maintain access to specific files even after the app or device restarts. This is particularly useful for applications that need to access files across multiple sessions.

Example: Persisting File Permissions

import { BusinessError } from '@kit.BasicServicesKit';
import { picker } from '@kit.CoreFileKit';
import { fileShare } from '@kit.CoreFileKit';

async function persistPermissionExample() {
    try {
        let DocumentSelectOptions = new picker.DocumentSelectOptions();
        let documentPicker = new picker.DocumentViewPicker();
        let uris = await documentPicker.select(DocumentSelectOptions);
        let policyInfo: fileShare.PolicyInfo = {
            uri: uris[0],
            operationMode: fileShare.OperationMode.READ_MODE,
        };
        let policies: Array<fileShare.PolicyInfo> = [policyInfo];
        fileShare.persistPermission(policies).then(() => {
            console.info("persistPermission successfully");
        }).catch((err: BusinessError<Array<fileShare.PolicyErrorResult>>) => {
            console.error("persistPermission failed with error message: " + err.message + ", error code: " + err.code);
            if (err.code == 13900001 && err.data) {
                for (let i = 0; i < err.data.length; i++) {
                    console.error("error code : " + JSON.stringify(err.data[i].code));
                    console.error("error uri : " + JSON.stringify(err.data[i].uri));
                    console.error("error reason : " + JSON.stringify(err.data[i].message));
                }
            }
        });
    } catch (error) {
        let err: BusinessError = error as BusinessError;
        console.error('persistPermission failed with err: ' + JSON.stringify(err));
    }
}
Enter fullscreen mode Exit fullscreen mode

Explanation

  1. DocumentSelectOptions and DocumentViewPicker: These classes are used to open a file picker dialog and allow the user to select a file. The selected file's URI is captured and stored in the uris array.
  2. PolicyInfo: This object defines the file access policy, including the URI of the file and the operation mode (e.g., read or write).
  3. persistPermission: This method persists the file permissions, allowing the application to access the file across sessions. The method returns a promise that resolves if the operation is successful or rejects with an error.

Notes

  1. Storing Persisted Authorization File Information: It is recommended to store persisted authorization file information locally for subsequent activation. This ensures that the application can quickly access the necessary files without needing to re-persist permissions.
  2. Activation After Restart: Persisted authorization data is stored in the system database and needs to be activated after app or device restart.
  3. Device Compatibility: The persistPermission interface only takes effect on 2in1 devices and requires permission.
  4. Clearing Authorization Data: Uninstalling the app will clear all authorization data.

Revoking File Permissions

Revoking file permissions is essential for managing access to sensitive files and ensuring that permissions are not misused. This process involves specifying the file URI and the operation mode, similar to persisting permissions.

Example: Revoking File Permissions

import { BusinessError } from '@kit.BasicServicesKit';
import { fileShare } from '@kit.CoreFileKit';

async function revokePermissionExample() {
    try {
        let uri = "file://docs/storage/Users/username/tmp.txt";
        let policyInfo: fileShare.PolicyInfo = {
            uri: uri,
            operationMode: fileShare.OperationMode.READ_MODE,
        };
        let policies: Array<fileShare.PolicyInfo> = [policyInfo];
        fileShare.revokePermission(policies).then(() => {
            console.info("revokePermission successfully");
        }).catch((err: BusinessError<Array<fileShare.PolicyErrorResult>>) => {
            console.error("revokePermission failed with error message: " + err.message + ", error code: " + err.code);
            if (err.code == 13900001 && err.data) {
                for (let i = 0; i < err.data.length; i++) {
                    console.error("error code : " + JSON.stringify(err.data[i].code));
                    console.error("error uri : " + JSON.stringify(err.data[i].uri));
                    console.error("error reason : " + JSON.stringify(err.data[i].message));
                }
            }
        });
    } catch (error) {
        let err: BusinessError = error as BusinessError;
        console.error('revokePermission failed with err: ' + JSON.stringify(err));
    }
}
Enter fullscreen mode Exit fullscreen mode

Explanation

  1. URI Specification: The URI of the file for which permissions are to be revoked is specified. This URI should match the one used during the persisting process.
  2. PolicyInfo: Similar to persisting permissions, a PolicyInfo object is created to define the file access policy.
  3. revokePermission: This method revokes the specified file permissions. The method returns a promise that resolves if the operation is successful or rejects with an error.

Notes

  1. URI Source: The URI in the example comes from the app's persisted data storage. Ensure that the URI is correctly formatted and accessible.
  2. Activation: Activate persisted permissions as needed. This ensures that the application can access the necessary files without needing to re-persist permissions.
  3. Device Compatibility: The revokePermission interface is only effective on 2in1 devices and requires permission.

Practical Use Cases

Secure File Access

  • Secure Storage: Use persisted permissions to securely store and access sensitive files across multiple sessions.
  • User Control: Allow users to control which files are accessible by the application, enhancing privacy and security.

Multi-Device Synchronization

  • File Synchronization: Ensure that files are synchronized across multiple devices by persisting permissions, allowing seamless access.
  • Cross-Device Access: Enable cross-device access to files, ensuring that users can access their data from any device running the same application.

Error Handling and Debugging

  • Error Logging: Implement comprehensive error logging to capture and diagnose issues related to file permissions.
  • User Feedback: Provide clear feedback to users when permissions are successfully persisted or revoked, enhancing the user experience.

Top comments (0)