diff --git a/src/lib/config.ts b/src/lib/config.ts index e0cae61..8ebaac2 100644 --- a/src/lib/config.ts +++ b/src/lib/config.ts @@ -129,6 +129,13 @@ const config = convict({ env: 'MOJALOOP_CALLBACK_URI', }, }, + overwriteExistingAccountsForUser: { + doc: + 'If true, when a user links a new account, the old accounts will be removed. This is useful for demo purposes. Defaults to `false`', + format: [true, false], + default: false, + env: 'OVERWRITE_EXISTING_ACCOUNTS_FOR_USER', + }, }) config.load({ diff --git a/src/repositories/account.ts b/src/repositories/account.ts index cac9364..e25f0ce 100644 --- a/src/repositories/account.ts +++ b/src/repositories/account.ts @@ -1,8 +1,10 @@ import firebase from '~/lib/firebase' import { DemoAccount } from '~/models/demoAccount' +import { logger } from '~/shared/logger' export interface IAccountRepository { insert(data: DemoAccount): Promise + deleteForUser(userId: string): Promise } export class FirebaseAccountRepository implements IAccountRepository { @@ -13,5 +15,31 @@ export class FirebaseAccountRepository implements IAccountRepository { await ref.set(data) return (data.id as unknown) as string } + + async deleteForUser(userId: string): Promise { + try { + const response = await firebase + .firestore() + .collection('accounts') + .where('userId', '==', userId) + .get() + + // Create a batch to perform all of the updates using a single request. + // Firebase will also execute the updates atomically according to the + // API specification. + const batch = firebase.firestore().batch() + + // Iterate through all matching documents add them to the processing batch. + response.docs.forEach((doc) => { + batch.delete(firebase.firestore().collection('accounts').doc(doc.id)) + }) + + // Commit the updates. + await batch.commit() + } catch (err) { + logger.error(err) + } + } } + export const accountRepository: IAccountRepository = new FirebaseAccountRepository() diff --git a/src/server/handlers/firestore/consents.ts b/src/server/handlers/firestore/consents.ts index 7806621..704180d 100644 --- a/src/server/handlers/firestore/consents.ts +++ b/src/server/handlers/firestore/consents.ts @@ -174,6 +174,11 @@ async function onConsentActivated(_server: StateServer, consent: Consent) { } try { + if (config.get('overwriteExistingAccountsForUser')) { + //replace the existing accounts for this user + await accountRepository.deleteForUser(consent.userId!) + } + if (consent.accounts!.length < 2) { // Create accounts for each of the linked accounts // TODO: revise consent to get the proper accountNickname fields