-
Notifications
You must be signed in to change notification settings - Fork 107
/
CieCardReaderScreen.tsx
555 lines (520 loc) · 18 KB
/
CieCardReaderScreen.tsx
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
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
/**
* A screen to guide the user to proper read the CIE
* TODO: isolate cie event listener as saga
* TODO: when 100% is reached, the animation end
*/
import {
ContentWrapper,
FooterWithButtons,
IOColors,
VSpacer
} from "@pagopa/io-app-design-system";
import cieManager, { Event as CEvent } from "@pagopa/react-native-cie";
import * as pot from "@pagopa/ts-commons/lib/pot";
import { Millisecond } from "@pagopa/ts-commons/lib/units";
import * as O from "fp-ts/lib/Option";
import { pipe } from "fp-ts/lib/function";
import * as React from "react";
import {
AccessibilityInfo,
Platform,
ScrollView,
StyleSheet,
Text,
Vibration,
View
} from "react-native";
import { connect } from "react-redux";
import CieNfcOverlay from "../../../components/cie/CieNfcOverlay";
import CieReadingCardAnimation, {
ReadingState
} from "../../../components/cie/CieReadingCardAnimation";
import { Body } from "../../../components/core/typography/Body";
import { ScreenContentHeader } from "../../../components/screens/ScreenContentHeader";
import TopScreenComponent from "../../../components/screens/TopScreenComponent";
import { isCieLoginUatEnabledSelector } from "../../../features/cieLogin/store/selectors";
import { getCieUatEndpoint } from "../../../features/cieLogin/utils/endpoints";
import I18n from "../../../i18n";
import { IOStackNavigationRouteProps } from "../../../navigation/params/AppParamsList";
import { AuthenticationParamsList } from "../../../navigation/params/AuthenticationParamsList";
import ROUTES from "../../../navigation/routes";
import {
CieAuthenticationErrorPayload,
CieAuthenticationErrorReason,
cieAuthenticationError
} from "../../../store/actions/cie";
import { resetToAuthenticationRoute } from "../../../store/actions/navigation";
import { ReduxProps } from "../../../store/actions/types";
import { assistanceToolConfigSelector } from "../../../store/reducers/backendStatus";
import { isNfcEnabledSelector } from "../../../store/reducers/cie";
import { GlobalState } from "../../../store/reducers/types";
import {
isScreenReaderEnabled,
setAccessibilityFocus
} from "../../../utils/accessibility";
import { isDevEnv } from "../../../utils/environment";
import { isIos } from "../../../utils/platform";
import { withTrailingPoliceCarLightEmojii } from "../../../utils/strings";
import {
assistanceToolRemoteConfig,
handleSendAssistanceLog
} from "../../../utils/supportAssistance";
import {
trackLoginCieCardReaderScreen,
trackLoginCieCardReadingError,
trackLoginCieCardReadingSuccess
} from "../analytics/cieAnalytics";
export type CieCardReaderScreenNavigationParams = {
ciePin: string;
authorizationUri: string;
};
type NavigationProps = IOStackNavigationRouteProps<
AuthenticationParamsList,
"CIE_CARD_READER_SCREEN"
>;
type Props = NavigationProps & ReduxProps & ReturnType<typeof mapStateToProps>;
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: IOColors.white
}
});
type State = {
// Get the current status of the card reading
readingState: ReadingState;
title: string;
subtitle: string;
content?: string;
errorMessage?: string;
isScreenReaderEnabled: boolean;
};
type setErrorParameter = {
eventReason: CieAuthenticationErrorReason;
errorDescription?: string;
navigation?: () => void;
};
// A subset of Cie Events (errors) which is of interest to analytics
const analyticActions = new Map<CieAuthenticationErrorReason, string>([
// Reading interrupted before the sdk complete the reading
["Transmission Error", I18n.t("authentication.cie.card.error.onTagLost")],
["ON_TAG_LOST", I18n.t("authentication.cie.card.error.onTagLost")],
[
"TAG_ERROR_NFC_NOT_SUPPORTED",
I18n.t("authentication.cie.card.error.unknownCardContent")
],
[
"ON_TAG_DISCOVERED_NOT_CIE",
I18n.t("authentication.cie.card.error.unknownCardContent")
],
["PIN Locked", I18n.t("authentication.cie.card.error.generic")],
["ON_CARD_PIN_LOCKED", I18n.t("authentication.cie.card.error.generic")],
["ON_PIN_ERROR", I18n.t("authentication.cie.card.error.tryAgain")],
["PIN_INPUT_ERROR", ""],
["CERTIFICATE_EXPIRED", I18n.t("authentication.cie.card.error.generic")],
["CERTIFICATE_REVOKED", I18n.t("authentication.cie.card.error.generic")],
["AUTHENTICATION_ERROR", I18n.t("authentication.cie.card.error.generic")],
[
"EXTENDED_APDU_NOT_SUPPORTED",
I18n.t("authentication.cie.nfc.apduNotSupported")
],
[
"ON_NO_INTERNET_CONNECTION",
I18n.t("authentication.cie.card.error.tryAgain")
],
["STOP_NFC_ERROR", ""],
["START_NFC_ERROR", ""]
]);
// the timeout we sleep until move to consent form screen when authentication goes well
const WAIT_TIMEOUT_NAVIGATION = 1700 as Millisecond;
const WAIT_TIMEOUT_NAVIGATION_ACCESSIBILITY = 5000 as Millisecond;
const VIBRATION = 100 as Millisecond;
const accessibityTimeout = 100 as Millisecond;
type TextForState = {
title: string;
subtitle: string;
content: string;
};
// some texts changes depending on current running Platform
const getTextForState = (
state: ReadingState.waiting_card | ReadingState.error,
errorMessage: string = ""
): TextForState => {
const texts: Record<
ReadingState.waiting_card | ReadingState.error,
TextForState
> = Platform.select({
ios: {
[ReadingState.waiting_card]: {
title: I18n.t("authentication.cie.card.titleiOS"),
subtitle: I18n.t("authentication.cie.card.layCardMessageHeaderiOS"),
// the native alert hides the screen content and shows a message it self
content: ""
},
[ReadingState.error]: {
title: I18n.t("authentication.cie.card.error.readerCardLostTitleiOS"),
subtitle: I18n.t(
"authentication.cie.card.error.readerCardLostHeaderiOS"
),
// the native alert hides the screen content and shows a message it self
content: ""
}
},
default: {
[ReadingState.waiting_card]: {
title: I18n.t("authentication.cie.card.title"),
subtitle: I18n.t("authentication.cie.card.layCardMessageHeader"),
content: I18n.t("authentication.cie.card.layCardMessageFooter")
},
[ReadingState.error]: {
title: I18n.t("authentication.cie.card.error.readerCardLostTitle"),
subtitle: I18n.t("authentication.cie.card.error.readerCardLostHeader"),
content: errorMessage
}
}
});
return texts[state];
};
/**
* This screen shown while reading the card
*/
class CieCardReaderScreen extends React.PureComponent<Props, State> {
private subTitleRef = React.createRef<Text>();
private choosenTool = assistanceToolRemoteConfig(
this.props.assistanceToolConfig
);
constructor(props: Props) {
super(props);
trackLoginCieCardReaderScreen();
this.state = {
/*
These are the states that can occur when reading the cie (from SDK)
- waiting_card (we are ready for read ->radar effect)
- reading (we are reading the card -> progress animation)
- error (the reading is interrupted -> progress animation stops and the progress circle becomes red)
- completed (the reading has been completed)
*/
readingState: ReadingState.waiting_card,
...getTextForState(ReadingState.waiting_card),
isScreenReaderEnabled: false
};
this.startCieiOS = this.startCieiOS.bind(this);
this.startCieAndroid = this.startCieAndroid.bind(this);
}
get ciePin(): string {
return this.props.route.params.ciePin;
}
get cieAuthorizationUri(): string {
return this.props.route.params.authorizationUri;
}
private setError = ({
eventReason,
errorDescription,
navigation
}: setErrorParameter) => {
const cieDescription =
errorDescription ??
pipe(
analyticActions.get(eventReason),
O.fromNullable,
O.getOrElse(() => "")
);
this.dispatchAnalyticEvent({
reason: eventReason,
cieDescription
});
this.setState(
{
readingState: ReadingState.error,
errorMessage: cieDescription
},
() => {
Vibration.vibrate(VIBRATION);
navigation?.();
}
);
};
private dispatchAnalyticEvent = (error: CieAuthenticationErrorPayload) => {
this.props.dispatch(cieAuthenticationError(error));
};
private handleCieEvent = async (event: CEvent) => {
handleSendAssistanceLog(this.choosenTool, event.event);
switch (event.event) {
// Reading starts
case "ON_TAG_DISCOVERED":
if (this.state.readingState !== ReadingState.reading) {
this.setState({ readingState: ReadingState.reading }, () => {
Vibration.vibrate(VIBRATION);
});
}
break;
case "Transmission Error":
case "ON_TAG_LOST":
case "TAG_ERROR_NFC_NOT_SUPPORTED":
case "ON_TAG_DISCOVERED_NOT_CIE":
case "AUTHENTICATION_ERROR":
case "ON_NO_INTERNET_CONNECTION":
case "EXTENDED_APDU_NOT_SUPPORTED":
this.setError({ eventReason: event.event });
break;
// The card is temporarily locked. Unlock is available by CieID app
case "PIN Locked":
case "ON_CARD_PIN_LOCKED":
case "ON_PIN_ERROR":
this.setError({
eventReason: event.event,
navigation: () =>
this.props.navigation.navigate(ROUTES.AUTHENTICATION, {
screen: ROUTES.CIE_WRONG_PIN_SCREEN,
params: {
remainingCount:
event.event === "ON_CARD_PIN_LOCKED" ? 0 : event.attemptsLeft
}
})
});
break;
// CIE is Expired or Revoked
case "CERTIFICATE_EXPIRED":
case "CERTIFICATE_REVOKED":
this.setError({
eventReason: event.event,
navigation: () =>
this.props.navigation.navigate(ROUTES.AUTHENTICATION, {
screen: ROUTES.CIE_EXPIRED_SCREEN
})
});
break;
default:
break;
}
this.updateContent();
};
private announceUpdate = () => {
if (this.state.content) {
AccessibilityInfo.announceForAccessibility(this.state.content);
}
};
private updateContent = () => {
switch (this.state.readingState) {
case ReadingState.reading:
this.setState(
{
title: I18n.t("authentication.cie.card.readerCardTitle"),
subtitle: I18n.t("authentication.cie.card.readerCardHeader"),
content: I18n.t("authentication.cie.card.readerCardFooter")
},
this.announceUpdate
);
break;
case ReadingState.error:
trackLoginCieCardReadingError();
this.setState(
state => getTextForState(ReadingState.error, state.errorMessage),
this.announceUpdate
);
break;
case ReadingState.completed:
this.setState(
state => ({
title: I18n.t("global.buttons.ok2"),
subtitle: I18n.t("authentication.cie.card.cieCardValid"),
// duplicate message so screen reader can read the updated message
content: state.isScreenReaderEnabled
? I18n.t("authentication.cie.card.cieCardValid")
: undefined
}),
this.announceUpdate
);
break;
// waiting_card state
default:
this.setState(
getTextForState(ReadingState.waiting_card),
this.announceUpdate
);
}
};
// TODO: It should reset authentication process
private handleCieError = (error: Error) => {
trackLoginCieCardReadingError();
handleSendAssistanceLog(this.choosenTool, error.message);
this.setError({ eventReason: "GENERIC", errorDescription: error.message });
};
private handleCieSuccess = (cieConsentUri: string) => {
if (this.state.readingState === ReadingState.completed) {
return;
}
handleSendAssistanceLog(this.choosenTool, "authentication SUCCESS");
this.setState({ readingState: ReadingState.completed }, () => {
this.updateContent();
setTimeout(
async () => {
trackLoginCieCardReadingSuccess();
this.props.navigation.navigate(ROUTES.AUTHENTICATION, {
screen: ROUTES.CIE_CONSENT_DATA_USAGE,
params: {
cieConsentUri
}
});
// if screen reader is enabled, give more time to read the success message
},
this.state.isScreenReaderEnabled
? WAIT_TIMEOUT_NAVIGATION_ACCESSIBILITY
: // if is iOS don't wait. The thank you page is shown natively
Platform.select({ ios: 0, default: WAIT_TIMEOUT_NAVIGATION })
);
});
};
public async startCieAndroid(useCieUat: boolean) {
cieManager
.start()
.then(async () => {
cieManager.onEvent(this.handleCieEvent);
cieManager.onError(this.handleCieError);
cieManager.onSuccess(this.handleCieSuccess);
await cieManager.setPin(this.ciePin);
cieManager.setAuthenticationUrl(this.cieAuthorizationUri);
cieManager.enableLog(isDevEnv);
cieManager.setCustomIdpUrl(useCieUat ? getCieUatEndpoint() : null);
await cieManager.startListeningNFC();
this.setState({ readingState: ReadingState.waiting_card });
})
.catch(() => {
this.setState({ readingState: ReadingState.error });
});
}
public async startCieiOS(useCieUat: boolean) {
cieManager.removeAllListeners();
cieManager.onEvent(this.handleCieEvent);
cieManager.onError(this.handleCieError);
cieManager.onSuccess(this.handleCieSuccess);
cieManager.enableLog(isDevEnv);
cieManager.setCustomIdpUrl(useCieUat ? getCieUatEndpoint() : null);
await cieManager.setPin(this.ciePin);
cieManager.setAuthenticationUrl(this.cieAuthorizationUri);
cieManager
.start({
readingInstructions: I18n.t(
"authentication.cie.card.iosAlert.readingInstructions"
),
moreTags: I18n.t("authentication.cie.card.iosAlert.moreTags"),
readingInProgress: I18n.t(
"authentication.cie.card.iosAlert.readingInProgress"
),
readingSuccess: I18n.t(
"authentication.cie.card.iosAlert.readingSuccess"
),
invalidCard: I18n.t("authentication.cie.card.iosAlert.invalidCard"),
tagLost: I18n.t("authentication.cie.card.iosAlert.tagLost"),
cardLocked: I18n.t("authentication.cie.card.iosAlert.cardLocked"),
wrongPin1AttemptLeft: I18n.t(
"authentication.cie.card.iosAlert.wrongPin1AttemptLeft"
),
wrongPin2AttemptLeft: I18n.t(
"authentication.cie.card.iosAlert.wrongPin2AttemptLeft"
),
genericError: I18n.t("authentication.cie.card.iosAlert.genericError")
})
.then(async () => {
await cieManager.startListeningNFC();
this.setState({ readingState: ReadingState.waiting_card });
})
.catch(() => {
this.setState({ readingState: ReadingState.error });
});
}
public async componentDidMount() {
const startCie = Platform.select({
ios: this.startCieiOS,
default: this.startCieAndroid
});
await startCie(this.props.isCieUatEnabled);
const srEnabled = await isScreenReaderEnabled();
this.setState({ isScreenReaderEnabled: srEnabled });
}
// focus on subtitle just after set the focus on navigation header title
private handleOnHeaderFocus = () => {
setAccessibilityFocus(this.subTitleRef, accessibityTimeout);
};
private handleCancel = () => resetToAuthenticationRoute();
private getFooter = () =>
Platform.select({
default: (
<FooterWithButtons
type="SingleButton"
primary={{
type: "Outline",
buttonProps: {
label: I18n.t("global.buttons.cancel"),
accessibilityLabel: I18n.t("global.buttons.cancel"),
onPress: this.handleCancel
}
}}
/>
),
ios: (
<FooterWithButtons
type="TwoButtonsInlineThird"
primary={{
type: "Outline",
buttonProps: {
label: I18n.t("global.buttons.cancel"),
accessibilityLabel: I18n.t("global.buttons.cancel"),
onPress: this.handleCancel
}
}}
secondary={{
type: "Solid",
buttonProps: {
label: I18n.t("authentication.cie.nfc.retry"),
accessibilityLabel: I18n.t("authentication.cie.nfc.retry"),
onPress: () => this.startCieiOS(this.props.isCieUatEnabled)
}
}}
/>
)
});
public render(): React.ReactNode {
return (
<TopScreenComponent
onAccessibilityNavigationHeaderFocus={this.handleOnHeaderFocus}
goBack={true}
headerTitle={withTrailingPoliceCarLightEmojii(
I18n.t("authentication.cie.card.headerTitle"),
this.props.isCieUatEnabled
)}
>
<ScreenContentHeader title={this.state.title} />
<ScrollView contentContainerStyle={{ flexGrow: 1 }}>
<ContentWrapper>
<Body ref={this.subTitleRef}>{this.state.subtitle}</Body>
{!isIos && (
<CieReadingCardAnimation readingState={this.state.readingState} />
)}
{isIos && <VSpacer size={16} />}
<Body accessible={true}>{this.state.content}</Body>
</ContentWrapper>
</ScrollView>
{this.state.readingState !== ReadingState.completed && // TODO: validate - the screen has the back button on top left so it includes cancel also on reading success
this.getFooter()}
</TopScreenComponent>
);
}
}
const mapStateToProps = (state: GlobalState) => {
const isEnabled = isNfcEnabledSelector(state);
return {
isNfcEnabled: pot.getOrElse(isEnabled, false),
assistanceToolConfig: assistanceToolConfigSelector(state),
isCieUatEnabled: isCieLoginUatEnabledSelector(state)
};
};
const ReaderScreen = (props: Props) => (
<View style={styles.container}>
{props.isNfcEnabled ? (
<CieCardReaderScreen {...props} />
) : (
<CieNfcOverlay {...props} />
)}
</View>
);
export default connect(mapStateToProps)(ReaderScreen);