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 AccountAssociation from '../bean/data/AccountAssociation'; 17import AuthorizedAccount from '../bean/data/AuthorizedAccount'; 18import { HiLog } from '../common/HiLog'; 19import { isInvalidStr } from '../common/FileUtils/utils'; 20 21const TAG: string = 'AssocConvertor'; 22 23interface AuthorizedAccountJson { 24 mUserAccount: string; 25 mTimestamp: number; 26} 27 28interface AccountAssociationJson { 29 accountId: string; 30 authorizedAccounts: AuthorizedAccountJson[]; 31} 32 33export default class AccountAssociationConvertor { 34 private constructor() { 35 } 36 37 public static convertToAccountAssociation(origin: string): AccountAssociation | null { 38 if (isInvalidStr(origin)) { 39 HiLog.error(TAG, 'The input origin string is invalid.'); 40 return null; 41 } 42 43 let accountAssociationJson: AccountAssociationJson | undefined = undefined; 44 try { 45 accountAssociationJson = JSON.parse(origin); 46 } catch (err) { 47 HiLog.error(TAG, `JSON parse error. ${err}`); 48 return null; 49 } 50 if (!accountAssociationJson || !accountAssociationJson.accountId || !accountAssociationJson.authorizedAccounts) { 51 HiLog.error(TAG, 'Parse account association json failed.'); 52 return null; 53 } 54 55 let authorizedAccountsJson = accountAssociationJson.authorizedAccounts; 56 let authorizedAccounts: AuthorizedAccount[] = []; 57 let accountId: string = accountAssociationJson.accountId; 58 59 for (const account of authorizedAccountsJson) { 60 if (isInvalidStr(account.mUserAccount)) { 61 HiLog.error(TAG, 'Obtain authorizedAccountsJson userAccount failed.'); 62 return null 63 } 64 if (account.mTimestamp === undefined || isNaN(account.mTimestamp)) { 65 HiLog.error(TAG, 'Obtain authorizedAccountsJson timestamp failed.'); 66 return null; 67 } 68 authorizedAccounts.push(new AuthorizedAccount(account.mUserAccount, account.mTimestamp)); 69 } 70 71 return new AccountAssociation(accountId, authorizedAccounts); 72 } 73}