Skip to content

Commit

Permalink
feat: overwrite accounts on linking (#57)
Browse files Browse the repository at this point in the history
* feat: optionally delete existing accounts for user

* feat: optionally delete existing accounts for user

* chore: linter
  • Loading branch information
lewisdaly authored Mar 22, 2021
1 parent 15c7b18 commit 13240d3
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 0 deletions.
7 changes: 7 additions & 0 deletions src/lib/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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({
Expand Down
28 changes: 28 additions & 0 deletions src/repositories/account.ts
Original file line number Diff line number Diff line change
@@ -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<string>
deleteForUser(userId: string): Promise<void>
}

export class FirebaseAccountRepository implements IAccountRepository {
Expand All @@ -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<void> {
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()
5 changes: 5 additions & 0 deletions src/server/handlers/firestore/consents.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit 13240d3

Please sign in to comment.