-
Notifications
You must be signed in to change notification settings - Fork 47
/
PrivacyLock.tsx
107 lines (97 loc) · 2.73 KB
/
PrivacyLock.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
import {
SimplifiedAppStateStatus,
useAppStateContext,
} from "@contexts/AppStateContext";
import {
PrivacyLockContextI,
usePrivacyLockContext,
} from "@contexts/LocalAuthContext";
import { EnvironmentName, getEnvironment } from "@waveshq/walletkit-core";
import { useEffect } from "react";
import { BackHandler } from "react-native";
import { ThemedView } from "@components/themed";
import { tailwind } from "@tailwind";
import {
NativeLoggingProps,
useLogger,
} from "@shared-contexts/NativeLoggingProvider";
import { getReleaseChannel } from "@api/releaseChannel";
const APP_LAST_ACTIVE: { force: boolean; timestamp?: number } = {
force: false,
};
function shouldReauthenticate(): boolean {
if (APP_LAST_ACTIVE.force) {
return true;
}
const lastActive = APP_LAST_ACTIVE.timestamp;
if (lastActive === undefined) {
return true;
}
const env = getEnvironment(getReleaseChannel());
const timeout = env.name === EnvironmentName.Development ? 3000 : 60000;
return lastActive + timeout < Date.now();
}
export function PrivacyLock(): JSX.Element {
const privacyLock = usePrivacyLockContext();
const appState = useAppStateContext();
const logger = useLogger();
const handler = (nextState: SimplifiedAppStateStatus): void => {
if (nextState === "background") {
APP_LAST_ACTIVE.timestamp = Date.now();
} else if (privacyLock.isEnabled) {
if (shouldReauthenticate()) {
authenticateOrExit(privacyLock, logger);
}
}
};
// authenticate once during cold start
useEffect(() => {
const id = appState.addListener(handler);
return () => appState.removeListener(id);
}, [handler]);
// this run only ONCE on fresh start
// isPrivacyLock change in-app should not re-triggered
useEffect(() => {
if (privacyLock.isEnabled) {
authenticateOrExit(privacyLock, logger);
}
}, []);
if (privacyLock.isAuthenticating || APP_LAST_ACTIVE.force) {
return (
<ThemedView
style={tailwind("h-full w-full")}
light={tailwind("bg-gray-200")}
dark={tailwind("bg-gray-900")}
/>
);
} else {
return <></>;
}
}
function authenticateOrExit(
privacyLockContext: PrivacyLockContextI,
logger: NativeLoggingProps
): void {
const backHandler = BackHandler.addEventListener(
"hardwareBackPress",
() => null
);
privacyLockContext
.prompt()
.then(async () => {
try {
APP_LAST_ACTIVE.force = false;
} catch (e) {
/* value not found in secure-store, unable to delete */
logger.error(e);
}
})
.catch(async (e) => {
logger.error(e);
APP_LAST_ACTIVE.force = true;
})
.finally(() => {
privacyLockContext.setIsAuthenticating(false);
backHandler.remove();
});
}