fxa_client/storage.rs
1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4
5//! # State management
6//!
7//! These are methods for managing the signed-in state of the application,
8//! either by restoring a previously-saved state via [`FirefoxAccount::from_json`]
9//! or by starting afresh with [`FirefoxAccount::new`].
10//!
11//! The application must persist the signed-in state after calling any methods
12//! that may alter it. Such methods are marked in the documentation as follows:
13//!
14//! **💾 This method alters the persisted account state.**
15//!
16//! After calling any such method, use [`FirefoxAccount::to_json`] to serialize
17//! the modified account state and persist the resulting string in application
18//! settings.
19
20use crate::{internal, ApiResult, Error, FirefoxAccount};
21use error_support::handle_error;
22use parking_lot::Mutex;
23
24#[uniffi::export]
25impl FirefoxAccount {
26 /// Restore a [`FirefoxAccount`] instance from serialized state.
27 ///
28 /// Given a JSON string previously obtained from [`FirefoxAccount::to_json`], this
29 /// method will deserialize it and return a live [`FirefoxAccount`] instance.
30 ///
31 /// **⚠️ Warning:** since the serialized state contains access tokens, you should
32 /// not call `from_json` multiple times on the same data. This would result
33 /// in multiple live objects sharing the same access tokens and is likely to
34 /// produce unexpected behaviour.
35 #[uniffi::constructor]
36 #[handle_error(Error)]
37 pub fn from_json(data: &str) -> ApiResult<FirefoxAccount> {
38 Ok(FirefoxAccount {
39 internal: Mutex::new(internal::FirefoxAccount::from_json(data)?),
40 })
41 }
42
43 /// Save current state to a JSON string.
44 ///
45 /// This method serializes the current account state into a JSON string, which
46 /// the application can use to persist the user's signed-in state across restarts.
47 /// The application should call this method and update its persisted state after
48 /// any potentially-state-changing operation.
49 ///
50 /// **⚠️ Warning:** the serialized state may contain encryption keys and access
51 /// tokens that let anyone holding them access the user's data in Firefox Sync
52 /// and/or other FxA services. Applications should take care to store the resulting
53 /// data in a secure fashion, as appropriate for their target platform.
54 #[handle_error(Error)]
55 pub fn to_json(&self) -> ApiResult<String> {
56 self.internal.lock().to_json()
57 }
58}