Skip to main content

tauri_plugin_biometric/
mobile.rs

1// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
2// SPDX-License-Identifier: Apache-2.0
3// SPDX-License-Identifier: MIT
4
5use serde::{Serialize, de::DeserializeOwned};
6use tauri::{
7    AppHandle, Runtime,
8    plugin::{PluginApi, PluginHandle},
9};
10
11use crate::models::*;
12
13#[cfg(target_os = "android")]
14const PLUGIN_IDENTIFIER: &str = "app.tauri.biometric";
15
16#[cfg(target_os = "ios")]
17tauri::ios_plugin_binding!(init_plugin_biometric);
18
19pub fn init<R: Runtime, C: DeserializeOwned>(
20    _app: &AppHandle<R>,
21    api: PluginApi<R, C>,
22) -> crate::Result<Biometric<R>> {
23    #[cfg(target_os = "android")]
24    let handle = api.register_android_plugin(PLUGIN_IDENTIFIER, "BiometricPlugin")?;
25    #[cfg(target_os = "ios")]
26    let handle = api.register_ios_plugin(init_plugin_biometric)?;
27    Ok(Biometric(handle))
28}
29
30/// Access to the biometric APIs.
31pub struct Biometric<R: Runtime>(PluginHandle<R>);
32
33#[derive(Serialize)]
34struct AuthenticatePayload {
35    reason: String,
36    #[serde(flatten)]
37    options: AuthOptions,
38}
39
40impl<R: Runtime> Biometric<R> {
41    /// Checks the device's availability and type of biometric authentication, as reported by the
42    /// operating system. Errors if the underlying mobile plugin invocation fails.
43    pub fn status(&self) -> crate::Result<Status> {
44        self.0.run_mobile_plugin("status", ()).map_err(Into::into)
45    }
46
47    /// Prompts the user for biometric authentication using the system UI (Android
48    /// `BiometricPrompt` or iOS `LocalAuthentication`), showing `reason` as the purpose of the
49    /// request. Resolves once the user is authenticated and errors if authentication fails, is
50    /// canceled, or the underlying mobile plugin invocation fails.
51    pub fn authenticate(&self, reason: String, options: AuthOptions) -> crate::Result<()> {
52        self.0
53            .run_mobile_plugin("authenticate", AuthenticatePayload { reason, options })
54            .map_err(Into::into)
55    }
56
57    /// Prompts the user for biometric authentication and, on success, encrypts
58    /// [`AuthOptions::data_to_encrypt`] or decrypts [`AuthOptions::data_to_decrypt`] using a key
59    /// protected by the device's strong biometrics. **Android only.**
60    pub fn biometric_cipher(
61        &self,
62        reason: String,
63        options: AuthOptions,
64    ) -> crate::Result<CipherResult> {
65        self.0
66            .run_mobile_plugin("biometricCipher", AuthenticatePayload { reason, options })
67            .map_err(Into::into)
68    }
69}