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
24impl FirefoxAccount {
25    /// Restore a [`FirefoxAccount`] instance from serialized state.
26    ///
27    /// Given a JSON string previously obtained from [`FirefoxAccount::to_json`], this
28    /// method will deserialize it and return a live [`FirefoxAccount`] instance.
29    ///
30    /// **⚠️ Warning:** since the serialized state contains access tokens, you should
31    /// not call `from_json` multiple times on the same data. This would result
32    /// in multiple live objects sharing the same access tokens and is likely to
33    /// produce unexpected behaviour.
34    #[handle_error(Error)]
35    pub fn from_json(data: &str) -> ApiResult<FirefoxAccount> {
36        Ok(FirefoxAccount {
37            internal: Mutex::new(internal::FirefoxAccount::from_json(data)?),
38        })
39    }
40
41    /// Save current state to a JSON string.
42    ///
43    /// This method serializes the current account state into a JSON string, which
44    /// the application can use to persist the user's signed-in state across restarts.
45    /// The application should call this method and update its persisted state after
46    /// any potentially-state-changing operation.
47    ///
48    /// **⚠️ Warning:** the serialized state may contain encryption keys and access
49    /// tokens that let anyone holding them access the user's data in Firefox Sync
50    /// and/or other FxA services. Applications should take care to store the resulting
51    /// data in a secure fashion, as appropriate for their target platform.
52    #[handle_error(Error)]
53    pub fn to_json(&self) -> ApiResult<String> {
54        self.internal.lock().to_json()
55    }
56}