1/* 2 * Copyright (c) 2025 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 AccountAssociationManager from '../manager/AccountAssociationManager'; 17import AuthorizedAccount from '../bean/data/AuthorizedAccount'; 18import { getOsAccountInfo } from '../common/FileUtils/utils'; 19import { HiLog } from '../common/HiLog'; 20import { osAccount } from '@kit.BasicServicesKit'; 21import Singleton from '../common/Singleton'; 22 23const TAG: string = 'AssociationSer'; 24 25export default class AccountAssociationService { 26 private static singletonInstance: Singleton<AccountAssociationService> = 27 new Singleton<AccountAssociationService>(() => new AccountAssociationService()); 28 29 public static getInstance(): AccountAssociationService { 30 return AccountAssociationService.singletonInstance.getInstance(); 31 } 32 33 public async getAuthorizedAccount(): Promise<string[]> { 34 HiLog.info(TAG, 'Enter getAuthorizedAccount.'); 35 let accountInfo: osAccount.OsAccountInfo | null = null; 36 try { 37 accountInfo = await getOsAccountInfo(); 38 } catch (err) { 39 HiLog.error(TAG, `getOsAccountInfo failed: ${JSON.stringify(err)}`); 40 return []; 41 } 42 43 const ownerAccountId: string = accountInfo.distributedInfo.name; 44 const associationMgr: AccountAssociationManager | null = AccountAssociationManager.getInstance(); 45 if (!associationMgr) { 46 HiLog.error(TAG, 'Get account association manager failed.'); 47 return []; 48 } 49 const authorizedAccounts: AuthorizedAccount[] = await associationMgr.getAuthorizedAccount(ownerAccountId); 50 let responseData: string[] = []; 51 authorizedAccounts.forEach(account => { 52 responseData.push(account.getUserAccount()); 53 }); 54 return responseData; 55 } 56 57 public async setAuthorizedAccount(authorizedAccount: string): Promise<void> { 58 HiLog.info(TAG, 'Enter setAuthorizedAccount.'); 59 let accountInfo: osAccount.OsAccountInfo | null = null; 60 try { 61 accountInfo = await getOsAccountInfo(); 62 } catch (err) { 63 HiLog.error(TAG, `getOsAccountInfo failed: ${JSON.stringify(err)}`); 64 return; 65 } 66 67 const ownerAccountId: string = accountInfo.distributedInfo.name; 68 const associationMgr: AccountAssociationManager | null = AccountAssociationManager.getInstance(); 69 if (!associationMgr) { 70 HiLog.error(TAG, 'Get account association manager failed.'); 71 return; 72 } 73 await associationMgr.setAuthorizedAccount(ownerAccountId, authorizedAccount); 74 } 75}