UNPKG

react-native-biometry

Version:
131 lines (109 loc) 2.83 kB
import { NativeModules } from 'react-native'; import { UnavailableError } from './unavailableError'; const { Biometry: RNBiometry } = NativeModules; export type BiometryPromptOptions = { title?: string; subtitle?: string; description?: string; cancelText?: string; }; export type BiometryAuthenticationOptions = { encryptedData?: string; prompt?: BiometryPromptOptions; securityKeyName?: string; }; export type BiometryAvailabilityResult = { available: boolean; biometryType?: string; error?: string; }; export type LocalAuthenticationResult = | { success: true; data: string } | { success: false; data: null; error: string; warning?: string }; export type EncryptDataParams = { input: string; securityKeyName?: string; }; export type EncryptDataResult = { data: string | null; success: boolean; }; const defaultPromptOptions: BiometryPromptOptions = { title: 'Authentication required', subtitle: '', description: '', cancelText: 'Cancel', }; export enum SecurityLevel { NONE = 0, SECRET = 1, BIOMETRIC = 2, } /** @public */ export class Biometry { static async isAvailable(): Promise<BiometryAvailabilityResult> { if (!RNBiometry?.isAvailable) { throw new UnavailableError(); } return RNBiometry.isAvailable(); } static async isEnrolled(): Promise<boolean> { if (!RNBiometry?.isEnrolled) { throw new UnavailableError(); } return RNBiometry.isEnrolled(); } static async getEnrolledLevel(): Promise<SecurityLevel> { if (!RNBiometry?.isEnrolled) { throw new UnavailableError(); } return RNBiometry.getEnrolledLevel(); } static async encryptData( params: EncryptDataParams ): Promise<EncryptDataResult> { if (!RNBiometry?.encryptData) { throw new UnavailableError(); } try { return await RNBiometry.encryptData(params); } catch (e: any) { return { data: null, success: false, }; } } static async authenticate( options: BiometryAuthenticationOptions = {} ): Promise<LocalAuthenticationResult> { if (!RNBiometry?.authenticate) { throw new UnavailableError(); } try { const prompt = { ...defaultPromptOptions, ...(options.prompt || {}), }; return RNBiometry.authenticate({ prompt, encryptedData: options.encryptedData?.length ? options.encryptedData : null, securityKeyName: options.securityKeyName?.length ? options.securityKeyName : null, }); } catch (e: any) { return { success: false, data: null, error: e.message, }; } } static async cancel(): Promise<void> { if (!RNBiometry?.cancel) { throw new UnavailableError(); } return RNBiometry.cancel(); } }