-
Notifications
You must be signed in to change notification settings - Fork 0
/
SelectAccountPresenter.swift
376 lines (327 loc) · 12.8 KB
/
SelectAccountPresenter.swift
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
//
// Nevis Mobile Authentication SDK Example App
//
// Copyright © 2022. Nevis Security AG. All rights reserved.
//
import NevisMobileAuthentication
/// Navigation parameter of the Select Account view.
enum SelectAccountParameter: NavigationParameterizable {
/// Represents account selection
/// .
/// - Parameters:
/// - accounts: The list of accounts.
/// - operation: The ongoing operation.
/// - handler: The account selection handler.
/// - message: The message to confirm.
case select(accounts: [any Account],
operation: Operation,
handler: AccountSelectionHandler?,
message: String?)
}
/// Presenter of Account Selection view.
final class SelectAccountPresenter {
// MARK: - Properties
/// The view of the presenter.
weak var view: BaseView?
/// The client provider.
private let clientProvider: ClientProvider
/// The authenticator selector used during in-band authentication.
private let authenticatorSelector: AuthenticatorSelector
/// The PIN changer.
private let pinChanger: PinChanger
/// The PIN user verifier.
private let pinUserVerifier: PinUserVerifier
/// The Password changer.
private let passwordChanger: PasswordChanger
/// The Password user verifier.
private let passwordUserVerifier: PasswordUserVerifier
/// The biometric user verifier.
private let biometricUserVerifier: BiometricUserVerifier
/// The device passcode user verifier.
private let devicePasscodeUserVerifier: DevicePasscodeUserVerifier
/// The application coordinator.
private let appCoordinator: AppCoordinator
/// The error handler chain.
private let errorHandlerChain: ErrorHandlerChain
/// The logger.
private let logger: SDKLogger
/// The ``MobileAuthenticationClient`` instance.
private var mobileAuthenticationClient: MobileAuthenticationClient? {
clientProvider.get()
}
/// The list of accounts.
private var accounts = [any Account]()
/// The current operation.
private var operation: Operation?
/// The account seelction handler.
private var handler: AccountSelectionHandler?
/// The transaction confirmation data.
private var transactionConfirmationData: String?
// MARK: - Initialization
/// Creates a new instance.
///
/// - Parameters:
/// - clientProvider: The client provider.
/// - authenticatorSelector: The authenticator selector used during in-band authentication.
/// - pinChanger: The PIN changer.
/// - pinUserVerifier: The PIN user verifier.
/// - passwordChanger: The Password changer.
/// - passwordUserVerifier: The Password user verifier.
/// - biometricUserVerifier: The biometric user verifier.
/// - devicePasscodeUserVerifier: The device passcode user verifier.
/// - appCoordinator: The application coordinator.
/// - errorHandlerChain: The error handler chain.
/// - logger: The logger.
/// - parameter: The navigation parameter.
init(clientProvider: ClientProvider,
authenticatorSelector: AuthenticatorSelector,
pinChanger: PinChanger,
pinUserVerifier: PinUserVerifier,
passwordChanger: PasswordChanger,
passwordUserVerifier: PasswordUserVerifier,
biometricUserVerifier: BiometricUserVerifier,
devicePasscodeUserVerifier: DevicePasscodeUserVerifier,
appCoordinator: AppCoordinator,
errorHandlerChain: ErrorHandlerChain,
logger: SDKLogger,
parameter: NavigationParameterizable) {
self.clientProvider = clientProvider
self.authenticatorSelector = authenticatorSelector
self.pinChanger = pinChanger
self.pinUserVerifier = pinUserVerifier
self.passwordChanger = passwordChanger
self.passwordUserVerifier = passwordUserVerifier
self.biometricUserVerifier = biometricUserVerifier
self.devicePasscodeUserVerifier = devicePasscodeUserVerifier
self.appCoordinator = appCoordinator
self.errorHandlerChain = errorHandlerChain
self.logger = logger
setParameter(parameter as? SelectAccountParameter)
}
/// :nodoc:
deinit {
os_log("SelectAccountPresenter", log: OSLog.deinit, type: .debug)
// If it is not nil at this moment, it means that a concurrent operation will be started.
handler?.cancel()
}
}
// MARK: - Public Interface
extension SelectAccountPresenter {
/// Returns the available accounts.
///
/// - Returns: The available accounts.
func getAccounts() -> [any Account] {
accounts
}
/// Selects the given account.
///
/// - Parameter account: The selected account.
func select(account: any Account) {
if let transactionConfirmationData {
// Transaction confirmation data is received from the SDK
// Show it to the user for confirmation or cancellation
// The AccountSelectionHandler will be invoked or cancelled there.
return confirm(transaction: transactionConfirmationData, using: account)
}
switch operation {
case .authentication:
// in-band authentication is in progress (arriving from the Home screen)
inBandAuthenticate(using: account)
case .deregistration:
deregister(using: account)
case .pinChange:
changePin(using: account)
case .passwordChange:
changePassword(using: account)
default:
handler?.username(account.username)
handler = nil
}
}
}
// MARK: - Private Interface
private extension SelectAccountPresenter {
/// Confirms the transaction.
///
/// - Parameters:
/// - transaction: The transaction that need to be confirmed or cancelled by the user.
/// - account: The current account.
func confirm(transaction: String, using account: any Account) {
let parameter: TransactionConfirmationParameter = .confirm(message: transaction,
account: account,
handler: handler!)
appCoordinator.navigateToTransactionConfirmation(with: parameter)
handler = nil
}
/// Starts an In-Band Authentication.
///
/// - Parameter account: The account that must be used to authenticate.
func inBandAuthenticate(using account: any Account, completion handler: ((Result<AuthorizationProvider?, AuthenticationError>) -> ())? = nil) {
mobileAuthenticationClient?.operations.authentication
.username(account.username)
.authenticatorSelector(authenticatorSelector)
.pinUserVerifier(pinUserVerifier)
.passwordUserVerifier(passwordUserVerifier)
.biometricUserVerifier(biometricUserVerifier)
.devicePasscodeUserVerifier(devicePasscodeUserVerifier)
.onSuccess { // (authorizationProvider: AuthorizationProvider) in
self.logger.log("In-band authentication succeeded.", color: .green)
self.printAuthorizationInfo($0)
if let handler {
return handler(.success($0))
}
self.appCoordinator.navigateToResult(with: .success(operation: self.operation!))
}
.onError { error in
self.logger.log("In-band authentication failed.", color: .red)
handler?(.failure(error))
switch error {
case let .FidoError(_, _, sessionProvider),
let .NetworkError(_, sessionProvider):
self.printSessionInfo(sessionProvider)
case .NoDeviceLockError:
fallthrough
case .Unknown:
fallthrough
@unknown default:
self.logger.log("In-band authentication failed because of an unknown error.", color: .red)
}
let operationError = OperationError(operation: .authentication, underlyingError: error)
self.errorHandlerChain.handle(error: operationError)
}
.execute()
}
/// Deregisters the given account.
///
/// - Parameter account: The account to deregister.
func deregister(using account: any Account) {
logger.log("Deregistering account: \(account)")
// Deregistration (Identity Suite env) is in progress where the deregistration endpoint is guarded,
// so an authorization provider is needed.
// First perform In-Band authentication then a deregistration with the username.
inBandAuthenticate(using: account) { result in
switch result {
case let .success(authorizationProvider):
guard let authorizationProvider else {
return self.errorHandlerChain.handle(error: AppError.cookieNotFound)
}
guard let authenticators = self.mobileAuthenticationClient?.localData.authenticators else {
return self.appCoordinator.navigateToResult(with: .success(operation: .deregistration))
}
let registeredAuthenticators = authenticators.filter {
$0.registration.isRegistered(account.username)
}
self.doDeregistration(for: account.username,
aaids: Set(registeredAuthenticators.map(\.aaid)),
authorizationProvider: authorizationProvider)
case .failure:
self.logger.log("Deregistration failed for user \(account.username)", color: .red)
}
}
}
/// Deregisters all authenticators of a given account.
///
/// - Parameters:
/// - accounts: The account to deregister.
/// - aaids: The list of authenticator AAIDs to deregister.
func doDeregistration(for username: String, aaids: Set<String>, authorizationProvider: AuthorizationProvider) {
var remainingAaids = aaids
guard let aaid = remainingAaids.popFirst() else {
logger.log("Deregistration succeeded for user \(username)", color: .green)
return appCoordinator.navigateToResult(with: .success(operation: operation!))
}
mobileAuthenticationClient?.operations.deregistration
.username(username)
.aaid(aaid)
.authorizationProvider(authorizationProvider)
.onSuccess {
self.logger.log("Deregistration succeeded for authenticator with aaid \(aaid) for user \(username)", color: .green)
self.doDeregistration(for: username,
aaids: remainingAaids,
authorizationProvider: authorizationProvider)
}
.onError {
self.logger.log("Deregistration failed for user \(username)", color: .red)
let operationError = OperationError(operation: .deregistration, underlyingError: $0)
self.errorHandlerChain.handle(error: operationError)
}
.execute()
}
/// Changes the PIN of the selected account.
///
/// - Parameter account: The seleced account.
func changePin(using account: any Account) {
logger.log("Changing PIN for account: \(account)")
view?.disableInteraction()
mobileAuthenticationClient?.operations.pinChange
.username(account.username)
.pinChanger(pinChanger)
.onSuccess {
self.logger.log("PIN change succeeded.", color: .green)
self.appCoordinator.navigateToResult(with: .success(operation: .pinChange))
}
.onError {
self.logger.log("PIN change failed.", color: .red)
let operationError = OperationError(operation: .pinChange, underlyingError: $0)
self.errorHandlerChain.handle(error: operationError)
}
.execute()
}
/// Changes the Password of the selected account.
///
/// - Parameter account: The seleced account.
func changePassword(using account: any Account) {
logger.log("Changing Password for account: \(account)")
view?.disableInteraction()
mobileAuthenticationClient?.operations.passwordChange
.username(account.username)
.passwordChanger(passwordChanger)
.onSuccess {
self.logger.log("Password change succeeded.", color: .green)
self.appCoordinator.navigateToResult(with: .success(operation: .passwordChange))
}
.onError {
self.logger.log("Password change failed.", color: .red)
let operationError = OperationError(operation: .passwordChange, underlyingError: $0)
self.errorHandlerChain.handle(error: operationError)
}
.execute()
}
/// Handles the recevied parameter.
///
/// - Parameter paramter: The parameter to handle.
func setParameter(_ parameter: SelectAccountParameter?) {
guard let parameter else {
preconditionFailure("Parameter type mismatch!")
}
switch parameter {
case let .select(accounts, operation, handler, transactionConfirmationData):
self.accounts = accounts
self.operation = operation
self.handler = handler
self.transactionConfirmationData = transactionConfirmationData
}
}
/// Prints authorization information to the console.
///
/// - Parameter authorizationProvider: The ``AuthorizationProvider`` holding the authorization information.
func printAuthorizationInfo(_ authorizationProvider: AuthorizationProvider?) {
if let cookieAuthorizationProvider = authorizationProvider as? CookieAuthorizationProvider {
logger.log("Received cookies: \(cookieAuthorizationProvider.cookies)")
}
else if let jwtAuthorizationProvider = authorizationProvider as? JwtAuthorizationProvider {
logger.log("Received JWT is \(jwtAuthorizationProvider.jwt)")
}
}
/// Prints session information to the console.
///
/// - Parameter sessionProvider: The ``SessionProvider`` holding the session information.
func printSessionInfo(_ sessionProvider: SessionProvider?) {
if let cookieSessionProvider = sessionProvider as? CookieSessionProvider {
logger.log("Received cookies: \(cookieSessionProvider.cookies)")
}
else if let jwtSessionProvider = sessionProvider as? JwtSessionProvider {
logger.log("Received JWT is \(jwtSessionProvider.jwt)")
}
}
}