tauri_plugin_biometric/
lib.rs

1// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
2// SPDX-License-Identifier: Apache-2.0
3// SPDX-License-Identifier: MIT
4
5#![cfg(mobile)]
6
7use serde::Serialize;
8use tauri::{
9    plugin::{Builder, PluginHandle, TauriPlugin},
10    Manager, Runtime,
11};
12
13pub use models::*;
14
15mod error;
16mod models;
17
18pub use error::{Error, Result};
19
20#[cfg(target_os = "android")]
21const PLUGIN_IDENTIFIER: &str = "app.tauri.biometric";
22
23#[cfg(target_os = "ios")]
24tauri::ios_plugin_binding!(init_plugin_biometric);
25
26/// Access to the biometric APIs.
27pub struct Biometric<R: Runtime>(PluginHandle<R>);
28
29#[derive(Serialize)]
30struct AuthenticatePayload {
31    reason: String,
32    #[serde(flatten)]
33    options: AuthOptions,
34}
35
36impl<R: Runtime> Biometric<R> {
37    pub fn status(&self) -> crate::Result<Status> {
38        self.0.run_mobile_plugin("status", ()).map_err(Into::into)
39    }
40
41    pub fn authenticate(&self, reason: String, options: AuthOptions) -> crate::Result<()> {
42        self.0
43            .run_mobile_plugin("authenticate", AuthenticatePayload { reason, options })
44            .map_err(Into::into)
45    }
46}
47
48/// Extensions to [`tauri::App`], [`tauri::AppHandle`], [`tauri::WebviewWindow`], [`tauri::Webview`] and [`tauri::Window`] to access the biometric APIs.
49pub trait BiometricExt<R: Runtime> {
50    fn biometric(&self) -> &Biometric<R>;
51}
52
53impl<R: Runtime, T: Manager<R>> crate::BiometricExt<R> for T {
54    fn biometric(&self) -> &Biometric<R> {
55        self.state::<Biometric<R>>().inner()
56    }
57}
58
59/// Initializes the plugin.
60pub fn init<R: Runtime>() -> TauriPlugin<R> {
61    Builder::new("biometric")
62        .setup(|app, api| {
63            #[cfg(target_os = "android")]
64            let handle = api.register_android_plugin(PLUGIN_IDENTIFIER, "BiometricPlugin")?;
65            #[cfg(target_os = "ios")]
66            let handle = api.register_ios_plugin(init_plugin_biometric)?;
67            app.manage(Biometric(handle));
68            Ok(())
69        })
70        .build()
71}