• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1/*
2 * Copyright (c) 2023 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 *     http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16import dlpPermission from '@ohos.dlpPermission';
17import fs from '@ohos.file.fs';
18import account from '@ohos.account.distributedAccount'
19import account_osAccount from '@ohos.account.osAccount';
20import Want from '@ohos.app.ability.Want';
21import { BusinessError } from '@ohos.base';
22import common from '@ohos.app.ability.common';
23import { PreferencesManager } from '../feature/PreferencesManager';
24import Logger from '../util/Logger';
25
26const TAG: string = 'DlpManager';
27const SOURCEURI: string = 'file://docs/storage/Users/currentUser';
28let context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext;
29let accountAbility = account.getDistributedAccountAbility();
30// 用户列表
31let userList: Array<dlpPermission.AuthUser> = [{
32  'authAccount': '123@ohos.com',
33  'authAccountType': dlpPermission.AccountType.CLOUD_ACCOUNT,
34  'dlpFileAccess': dlpPermission.DLPFileAccess.READ_ONLY,
35  // 授权到期时间戳
36  'permExpiryTime': 8888520175,
37}, {
38  'authAccount': '456@ohos.com',
39  'authAccountType': dlpPermission.AccountType.CLOUD_ACCOUNT,
40  'dlpFileAccess': dlpPermission.DLPFileAccess.FULL_CONTROL,
41  // 授权到期时间戳
42  'permExpiryTime': 8888520175,
43}]
44
45// dlp信息类型
46export class TestDlpFileInfo {
47  plaintextPath: string = '';
48  ciphertextPath: string = '';
49}
50
51// 用户信息类型
52interface UserInfo {
53  name: string,
54  id: string,
55  event: string,
56  nickname: string,
57  avatar: string
58}
59
60export class DlpManager {
61  // linkFile文件名
62  private linkFileName: string = '';
63  // link地址文件名
64  private linkFilePath: string = '';
65  // dlp文件
66  private dlpFile: dlpPermission.DLPFile = {} as dlpPermission.DLPFile;
67  // 沙箱包名
68  private sandboxBundleName: string = 'com.example.fileEdit';
69  private sandboxAbilityName: string = 'EntryAbility';
70  // dlp文件的句柄
71  private dlpFd: number = -1;
72  // 账号信息
73  private accountInfo?: account_osAccount.OsAccountInfo;
74  // dlp文件路径地址
75  private dlpFileUri: string = '';
76  private preferencesManager: PreferencesManager = new PreferencesManager();
77
78  constructor() {
79  }
80
81  // 获取用户id
82  async getUserId(): Promise<number> {
83    let accountMgr = account_osAccount.getAccountManager();
84    return await accountMgr.getOsAccountLocalIdFromProcess();
85  }
86
87  // 获取帐号信息
88  async getOsAccountInfo(): Promise<account_osAccount.OsAccountInfo> {
89    let accountMgr = account_osAccount.getAccountManager();
90    return await accountMgr.getCurrentOsAccount();
91  }
92
93  // 获取AuthPerm
94  getAuthPerm(accountName: string, dlpProperty: dlpPermission.DLPProperty): dlpPermission.DLPFileAccess {
95    let perm: dlpPermission.DLPFileAccess = dlpPermission.DLPFileAccess.NO_PERMISSION;
96    if (accountName === dlpProperty.ownerAccount) {
97      return dlpPermission.DLPFileAccess.FULL_CONTROL;
98    }
99    if ((dlpProperty.everyoneAccessList !== undefined) && (dlpProperty.everyoneAccessList.length > 0)) {
100      perm = Math.max(...dlpProperty.everyoneAccessList);
101    }
102    let authUserList = dlpProperty.authUserList ?? [];
103    for (let i = 0; i < authUserList.length; ++i) {
104      let authUser = authUserList[i];
105      if (authUser.authAccount === accountName) {
106        return authUser.dlpFileAccess;
107      }
108    }
109    return perm;
110  }
111
112  // 帐号登录
113  async AccountLogin(accountName: string) {
114    Logger.info('AccountLogin start');
115    await this.AccountLogout();
116    let info: UserInfo = {
117      name: '',
118      id: '1234',
119      event: 'Ohos.account.event.LOGIN',
120      nickname: 'nickname',
121      avatar: 'avatar'
122    };
123    info.name = accountName;
124    info.event = 'Ohos.account.event.LOGIN';
125    try {
126      await accountAbility.setOsAccountDistributedInfo(info);
127    } catch (err) {
128      console.error(TAG, `setOsAccountDistributedInfo LOGIN failed${err.code}, message:${err.message}`);
129      return
130    }
131    let user = await accountAbility.getOsAccountDistributedInfo();
132    Logger.info(`CurrentMessage is ${JSON.stringify(user)}`);
133  }
134
135  // 帐号登出
136  async AccountLogout() {
137    Logger.info('AccountLogout start');
138    let accountInfo = await accountAbility.getOsAccountDistributedInfo();
139    let info: UserInfo = {
140      name: '',
141      id: '1234',
142      event: 'Ohos.account.event.LOGIN',
143      nickname: 'nickname',
144      avatar: 'avatar'
145    }
146    if (accountInfo.name === 'ohosAnonymousName') {
147      return
148    }
149    info.name = accountInfo.name
150    info.event = 'Ohos.account.event.LOGOUT'
151    await accountAbility.setOsAccountDistributedInfo(info);
152    Logger.info('AccountLogout end');
153  }
154
155  // 生成可选参数的DLP策略
156  async genTestOptionalDlpProperty(): Promise<dlpPermission.DLPProperty> {
157    let accountInfo = await this.getOsAccountInfo();
158    let property: dlpPermission.DLPProperty = {
159      'ownerAccount': accountInfo.distributedInfo.name,
160      'ownerAccountID': accountInfo.distributedInfo.id,
161      'ownerAccountType': dlpPermission.AccountType.CLOUD_ACCOUNT,
162      'contactAccount': accountInfo.distributedInfo.name,
163      'offlineAccess': true,
164    };
165    return property;
166  }
167
168  // 生成DLP策略
169  async genTestDlpProperty(): Promise<dlpPermission.DLPProperty> {
170    this.accountInfo = await this.getOsAccountInfo();
171    let property: dlpPermission.DLPProperty = {
172      'ownerAccount': this.accountInfo.distributedInfo.name,
173      'ownerAccountID': this.accountInfo.distributedInfo.id,
174      'ownerAccountType': dlpPermission.AccountType.CLOUD_ACCOUNT,
175      'authUserList': userList,
176      'contactAccount': this.accountInfo.distributedInfo.name,
177      'offlineAccess': true,
178      'everyoneAccessList': [dlpPermission.DLPFileAccess.READ_ONLY],
179    };
180    return property;
181  }
182
183  // 启动沙箱应用
184  startSandboxApp(): void {
185    let want: Want = {
186      bundleName: this.sandboxBundleName,
187      abilityName: this.sandboxAbilityName,
188      uri: this.linkFilePath,
189      parameters: {
190        'linkFileName': {
191          'name': this.linkFileName
192        },
193        'uri': this.linkFilePath,
194        'dlpUri': {
195          'name': this.dlpFileUri
196        },
197      }
198    };
199    context.startAbility(want, (err) => {
200      Logger.info()
201    });
202  }
203
204  // 生成测试DLP文件
205  async genTestDlpFile(plaintextPath: string, ciphertextFd: number, displayName: string, currentPerssion: number, dlpFileInfos: Array<TestDlpFileInfo>) {
206    Logger.info('GenTestDlpFile start');
207    let file: fs.File = fs.openSync(plaintextPath, fs.OpenMode.READ_WRITE);
208    this.dlpFd = ciphertextFd;
209    this.dlpFileUri = `${SOURCEURI}/${displayName}`;
210    let fileInfo: TestDlpFileInfo = new TestDlpFileInfo();
211    fileInfo.plaintextPath = plaintextPath;
212    fileInfo.ciphertextPath = this.dlpFileUri;
213    dlpFileInfos.push(fileInfo);
214    AppStorage.set<Array<TestDlpFileInfo>>('dlpFileInfos', dlpFileInfos);
215    await this.preferencesManager.putDlpFileInfos(dlpFileInfos);
216    Logger.info(`file.fd:${file.fd},dlpFd:${this.dlpFd}`);
217    let property = await this.genTestDlpProperty();
218    property.everyoneAccessList = [currentPerssion + 1];
219    Logger.info(`everyoneList ${JSON.stringify(property.everyoneAccessList)},current`);
220    try {
221      this.dlpFile = await dlpPermission.generateDLPFile(file.fd, this.dlpFd, property);
222      if (await dlpPermission.isDLPFile(this.dlpFd)) {
223        Logger.info(`generateDLPFile success`);
224      } else {
225        Logger.info(`generateDLPFile fail`);
226      }
227      this.dlpFile.closeDLPFile();
228    }
229
230    catch (err) {
231      let error: BusinessError = err as BusinessError;
232      Logger.error(`generateDLPFile failed, errCode:${error.code},message:${error.message}`);
233      fs.closeSync(file.fd);
234      fs.closeSync(this.dlpFd);
235    }
236  }
237}
238
239
240