-
Notifications
You must be signed in to change notification settings - Fork 1
/
HomeViewModel.ts
381 lines (343 loc) · 12.1 KB
/
HomeViewModel.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
/**
* Copyright © 2023 Nevis Security AG. All rights reserved.
*/
import { useState } from 'react';
import {
Aaid,
Account,
Authenticator,
MobileAuthenticationClientInitializer,
} from '@nevis-security/nevis-mobile-authentication-sdk-react';
import { useNavigation } from '@react-navigation/native';
import type { NativeStackNavigationProp } from '@react-navigation/native-stack';
import type { RootStackParamList } from './RootStackParamList';
import { AppEnvironment, ConfigurationLoader } from '../configuration/ConfigurationLoader';
import {
AppErrorAccountsNotFound,
AppErrorDeviceInformationNotFound,
AppErrorPasswordAuthenticatorNotFound,
AppErrorPinAuthenticatorNotFound,
} from '../error/AppError';
import { ErrorHandler } from '../error/ErrorHandler';
import { AccountItem } from '../model/AccountItem';
import { OperationType } from '../model/OperationType';
import * as OutOfBandOperationHandler from '../userInteraction/OutOfBandOperationHandler';
import { PasswordChangerImpl } from '../userInteraction/PasswordChangerImpl';
import { PinChangerImpl } from '../userInteraction/PinChangerImpl';
import { ClientProvider } from '../utility/ClientProvider';
import * as RootNavigation from '../utility/RootNavigation';
const useHomeViewModel = () => {
const navigation = useNavigation<NativeStackNavigationProp<RootStackParamList>>();
const [localAccounts, setLocalAccounts] = useState<Array<Account>>([]);
const [localAuthenticators, setLocalAuthenticators] = useState<Array<Authenticator>>([]);
const [numberOfAccounts, setNumberOfAccounts] = useState<number>(0);
async function initClient() {
console.log('Initializing the client...');
const configuration = ConfigurationLoader.getInstance().sdkConfiguration;
await new MobileAuthenticationClientInitializer()
.configuration(configuration)
.onSuccess(async (mobileAuthenticationClient) => {
ClientProvider.getInstance().client = mobileAuthenticationClient;
console.log('Client received.');
fetchData();
})
.onError(ErrorHandler.handle.bind(null, OperationType.init))
.execute()
.catch(ErrorHandler.handle.bind(null, OperationType.init));
}
function handleDeepLink(url: string) {
const payload = url
.split('?')
.at(1)
?.split('&')
.filter((queryParam) => queryParam.split('=').at(0) == 'dispatchTokenResponse')
.at(0)
?.split('=')
.at(1);
console.log(`Dispatch token response: ${payload}`);
if (payload) {
OutOfBandOperationHandler.decodePayload(payload).catch(
ErrorHandler.handle.bind(null, OperationType.payloadDecode)
);
}
}
function fetchData() {
getAccounts().then(getAuthenticators).then(getDeviceInformation);
}
async function getAccounts() {
const client = ClientProvider.getInstance().client;
await client?.localData
.accounts()
.then((registeredAccounts) => {
if (registeredAccounts.length === 0) {
setNumberOfAccounts(0);
setLocalAccounts([]);
return console.log('There are no registered accounts.');
}
console.log('Registered accounts:');
registeredAccounts.forEach((account) => {
console.log(` ${JSON.stringify(account, null, ' ')}`);
});
setNumberOfAccounts(registeredAccounts.length);
setLocalAccounts(registeredAccounts);
})
.catch(ErrorHandler.handle.bind(null, OperationType.localData));
}
async function getAuthenticators() {
const client = ClientProvider.getInstance().client;
await client?.localData
.authenticators()
.then((authenticators) => {
if (authenticators.length === 0) {
return console.log('There are no available authenticators.');
}
console.log('Available authenticators:');
authenticators.forEach((authenticator) => {
console.log(` ${JSON.stringify(authenticator, null, ' ')}`);
});
setLocalAuthenticators(authenticators);
})
.catch(ErrorHandler.handle.bind(null, OperationType.localData));
}
async function getDeviceInformation() {
const client = ClientProvider.getInstance().client;
await client?.localData
.deviceInformation()
.then((deviceInformation) => {
if (!deviceInformation) {
return console.log('There is no available device info.');
}
console.log(
`Available device info: ${JSON.stringify(deviceInformation, null, ' ')}`
);
})
.catch(ErrorHandler.handle.bind(null, OperationType.localData));
}
function readQrCode() {
navigation.navigate('ReadQrCode');
}
function authCloudApiRegister() {
navigation.navigate('AuthCloudApiRegistration');
}
function inBandRegister() {
navigation.navigate('UsernamePasswordLogin');
}
function selectAccount(operation: OperationType) {
navigation.navigate('SelectAccount', {
items: localAccounts.map((account) => new AccountItem(account.username)),
operation: operation,
});
}
function inBandAuthenticate() {
if (localAccounts.length === 0) {
return ErrorHandler.handle(
OperationType.authentication,
new AppErrorAccountsNotFound('There are no registered accounts')
);
}
selectAccount(OperationType.authentication);
}
function deregister() {
const client = ClientProvider.getInstance().client;
if (localAccounts.length === 0) {
return ErrorHandler.handle(
OperationType.deregistration,
new AppErrorAccountsNotFound('There are no registered accounts')
);
}
if (ConfigurationLoader.getInstance().appEnvironment === AppEnvironment.IdentitySuite) {
// In the example app Identity Suite environment the deregistration endpoint is guarded,
// and as such we need to provide a cookie to the deregister call.
// Also on Identity Suite a deregistration has to be authenticated for every user,
// so batch deregistration is not really possible.
return selectAccount(OperationType.deregistration);
}
return localAccounts
.reduce(
(previous, account) => previous.then(startDeregistration.bind(null, account)),
Promise.resolve()
)
.then(() => {
navigation.navigate('Result', { operation: OperationType.deregistration });
})
.catch(ErrorHandler.handle.bind(null, OperationType.deregistration));
async function startDeregistration(account: Account) {
return new Promise<void>((resolve, reject) => {
client?.operations.deregistration
.username(account.username)
.onSuccess(() => {
console.log(
`Deregistration successful for account: ${JSON.stringify(
account,
null,
' '
)}`
);
resolve();
})
.onError(reject)
.execute()
.catch(reject);
console.log(
`Executing deregistration for account: ${JSON.stringify(account, null, ' ')}`
);
});
}
}
async function changeDeviceInformation() {
const client = ClientProvider.getInstance().client;
await client?.localData
.deviceInformation()
.then((deviceInformation) => {
if (!deviceInformation) {
throw new AppErrorDeviceInformationNotFound(
'There is no available device info.'
);
}
console.log(
`Available device info: ${JSON.stringify(deviceInformation, null, ' ')}`
);
navigation.navigate('DeviceInformationChange', {
name: deviceInformation.name,
});
})
.catch(ErrorHandler.handle.bind(null, OperationType.deviceInformationChange));
}
async function deleteLocalAuthenticators() {
const client = ClientProvider.getInstance().client;
if (localAccounts.length === 0) {
return ErrorHandler.handle(
OperationType.localData,
new AppErrorAccountsNotFound('There are no registered accounts')
);
}
return localAccounts
.reduce(
(previous, account) =>
previous.then(startLocalAuthenticatorDeletion.bind(null, account)),
Promise.resolve()
)
.then(() => {
navigation.navigate('Result', { operation: OperationType.localData });
})
.catch(ErrorHandler.handle.bind(null, OperationType.localData));
async function startLocalAuthenticatorDeletion(account: Account) {
return new Promise<void>((resolve, reject) => {
console.log(
`Executing deregistration for account: ${JSON.stringify(account, null, ' ')}`
);
client?.localData.deleteAuthenticator(account.username).then(resolve).catch(reject);
});
}
}
async function changePin() {
// we should only pass the accounts to the account selection that already have a pin enrollment
const filteredAuthenticators = localAuthenticators.filter((authenticator) => {
return authenticator.aaid === Aaid.PIN.rawValue();
});
const pinAuthenticator = filteredAuthenticators.at(0);
if (!pinAuthenticator) {
return ErrorHandler.handle(
OperationType.pinChange,
new AppErrorPinAuthenticatorNotFound(
'Pin change failed, there are no registered PIN authenticators'
)
);
}
const userEnrollment = pinAuthenticator.userEnrollment;
const eligibleAccounts = localAccounts.filter((account) => {
return userEnrollment.isEnrolled(account.username);
});
if (eligibleAccounts.length === 0) {
return ErrorHandler.handle(
OperationType.pinChange,
new AppErrorAccountsNotFound(`Pin change failed, no eligible accounts found`)
);
} else if (eligibleAccounts.length === 1) {
// in case that there is only one account, then we can select it automatically
console.log('Automatically selecting account for PIN Change');
await startPinChange(eligibleAccounts.at(0)!);
} else {
// in case that there are multiple eligible accounts then we have to show the account selection screen
return selectAccount(OperationType.pinChange);
}
async function startPinChange(account: Account) {
const client = ClientProvider.getInstance().client;
client?.operations.pinChange
.username(account.username)
.pinChanger(new PinChangerImpl())
.onSuccess(() => {
console.log('PIN Change succeeded.');
RootNavigation.navigate('Result', {
operation: OperationType.pinChange,
});
})
.onError(ErrorHandler.handle.bind(null, OperationType.pinChange))
.execute()
.catch(ErrorHandler.handle.bind(null, OperationType.pinChange));
}
}
async function changePassword() {
// we should only pass the accounts to the account selection that already have a password enrollment
const filteredAuthenticators = localAuthenticators.filter((authenticator) => {
return authenticator.aaid === Aaid.PASSWORD.rawValue();
});
const passwordAuthenticator = filteredAuthenticators.at(0);
if (!passwordAuthenticator) {
return ErrorHandler.handle(
OperationType.passwordChange,
new AppErrorPasswordAuthenticatorNotFound(
'Password change failed, there are no registered password authenticators'
)
);
}
const userEnrollment = passwordAuthenticator.userEnrollment;
const eligibleAccounts = localAccounts.filter((account) => {
return userEnrollment.isEnrolled(account.username);
});
if (eligibleAccounts.length === 0) {
return ErrorHandler.handle(
OperationType.passwordChange,
new AppErrorAccountsNotFound(`Password change failed, no eligible accounts found`)
);
} else if (eligibleAccounts.length === 1) {
// in case that there is only one account, then we can select it automatically
console.log('Automatically selecting account for password Change');
await startPasswordChange(eligibleAccounts.at(0)!);
} else {
// in case that there are multiple eligible accounts then we have to show the account selection screen
return selectAccount(OperationType.passwordChange);
}
async function startPasswordChange(account: Account) {
const client = ClientProvider.getInstance().client;
client?.operations.passwordChange
.username(account.username)
.passwordChanger(new PasswordChangerImpl())
.onSuccess(() => {
console.log('Password Change succeeded.');
RootNavigation.navigate('Result', {
operation: OperationType.passwordChange,
});
})
.onError(ErrorHandler.handle.bind(null, OperationType.passwordChange))
.execute()
.catch(ErrorHandler.handle.bind(null, OperationType.passwordChange));
}
}
return {
numberOfAccounts,
initClient,
fetchData,
handleDeepLink,
readQrCode,
authCloudApiRegister,
inBandRegister,
inBandAuthenticate,
deregister,
changeDeviceInformation,
deleteLocalAuthenticators,
changePin,
changePassword,
};
};
export default useHomeViewModel;