1 |
|
2 |
|
3 | import { NativeModules } from 'react-native';
|
4 |
|
5 | const { ExponentSecureStore } = NativeModules;
|
6 |
|
7 | export type KeychainAccessibilityConstant = number;
|
8 |
|
9 | export const AFTER_FIRST_UNLOCK: KeychainAccessibilityConstant =
|
10 | ExponentSecureStore.AFTER_FIRST_UNLOCK;
|
11 | export const AFTER_FIRST_UNLOCK_THIS_DEVICE_ONLY: KeychainAccessibilityConstant =
|
12 | ExponentSecureStore.AFTER_FIRST_UNLOCK_THIS_DEVICE_ONLY;
|
13 | export const ALWAYS: KeychainAccessibilityConstant = ExponentSecureStore.ALWAYS;
|
14 | export const WHEN_PASSCODE_SET_THIS_DEVICE_ONLY: KeychainAccessibilityConstant =
|
15 | ExponentSecureStore.WHEN_PASSCODE_SET_THIS_DEVICE_ONLY;
|
16 | export const ALWAYS_THIS_DEVICE_ONLY: KeychainAccessibilityConstant =
|
17 | ExponentSecureStore.ALWAYS_THIS_DEVICE_ONLY;
|
18 | export const WHEN_UNLOCKED: KeychainAccessibilityConstant = ExponentSecureStore.WHEN_UNLOCKED;
|
19 | export const WHEN_UNLOCKED_THIS_DEVICE_ONLY: KeychainAccessibilityConstant =
|
20 | ExponentSecureStore.WHEN_UNLOCKED_THIS_DEVICE_ONLY;
|
21 |
|
22 | export type SecureStoreOptions = {
|
23 | keychainService?: string,
|
24 | keychainAccessible?: KeychainAccessibilityConstant,
|
25 | };
|
26 |
|
27 | export async function deleteItemAsync(
|
28 | key: string,
|
29 | options: SecureStoreOptions = {}
|
30 | ): Promise<void> {
|
31 | _ensureValidKey(key);
|
32 | await ExponentSecureStore.deleteValueWithKeyAsync(key, options);
|
33 | }
|
34 |
|
35 | export async function getItemAsync(
|
36 | key: string,
|
37 | options: SecureStoreOptions = {}
|
38 | ): Promise<?string> {
|
39 | _ensureValidKey(key);
|
40 | return await ExponentSecureStore.getValueWithKeyAsync(key, options);
|
41 | }
|
42 |
|
43 | export async function setItemAsync(
|
44 | key: string,
|
45 | value: string,
|
46 | options: SecureStoreOptions = {}
|
47 | ): Promise<void> {
|
48 | _ensureValidKey(key);
|
49 | if (!_isValidValue(value)) {
|
50 | throw new Error(
|
51 | `Invalid value provided to SecureStore. Values must be strings; consider JSON-encoding your values if they are serializable.`
|
52 | );
|
53 | }
|
54 | await ExponentSecureStore.setValueWithKeyAsync(value, key, options);
|
55 | }
|
56 |
|
57 | function _ensureValidKey(key: string) {
|
58 | if (!_isValidKey(key)) {
|
59 | throw new Error(
|
60 | `Invalid key provided to SecureStore. Keys must not be empty and contain only alphanumeric characters, ".", "-", and "_".`
|
61 | );
|
62 | }
|
63 | }
|
64 |
|
65 | function _isValidKey(key: string) {
|
66 | return typeof key === 'string' && /^[\w.-]+$/.test(key);
|
67 | }
|
68 |
|
69 | function _isValidValue(value: string) {
|
70 | return typeof value === 'string';
|
71 | }
|