glacier-web 0.3.0

A batteries-included web framework for Rust, inspired by Rails, Phoenix and Laravel.
Documentation
//! Cookie-backed sessions and flash messages.
//!
//! The session is a JSON object stored in an encrypted cookie, so it is
//! private and tamper-proof but limited to roughly 4 KB. Store ids, not
//! records. It is loaded lazily on first use and only re-written when it
//! changes.

use std::sync::{Arc, Mutex, MutexGuard};

use serde::Serialize;
use serde::de::DeserializeOwned;
use serde_json::{Map, Value};

use crate::cookies::{Cookie, Cookies, SameSite};
use crate::error::Result;

pub(crate) const COOKIE_NAME: &str = "_glacier_session";
const FLASH_KEY: &str = "_flash";

#[derive(Clone)]
pub struct Session {
    state: Arc<Mutex<State>>,
    cookies: Cookies,
    secure: bool,
}

#[derive(Default)]
struct State {
    loaded: bool,
    dirty: bool,
    data: Map<String, Value>,
    /// Flash set by an earlier request (or `flash_now`), readable now.
    flash: Map<String, Value>,
    /// Whether this request read the flash, so it's spent.
    flash_read: bool,
    /// Kinds `put_flash` set during this request, for the next one.
    flash_set: Vec<String>,
}

impl Session {
    pub(crate) fn new(cookies: Cookies, secure: bool) -> Self {
        Self {
            state: Arc::default(),
            cookies,
            secure,
        }
    }

    fn state(&self) -> MutexGuard<'_, State> {
        let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner());
        if !state.loaded {
            state.loaded = true;
            if let Some(Value::Object(data)) = self
                .cookies
                .get_private(COOKIE_NAME)
                .and_then(|raw| serde_json::from_str(&raw).ok())
            {
                // Flash stays until a request reads it, as Rails' does: a
                // request that never looks (an asset, a 404) leaves it.
                if let Some(Value::Object(flash)) = data.get(FLASH_KEY) {
                    state.flash = flash.clone();
                }
                state.data = data;
            }
        }
        state
    }

    pub fn get<T: DeserializeOwned>(&self, key: &str) -> Option<T> {
        let value = self.state().data.get(key)?.clone();
        serde_json::from_value(value).ok()
    }

    pub fn insert<T: Serialize>(&self, key: &str, value: T) -> Result<()> {
        let value = serde_json::to_value(value)?;
        let mut state = self.state();
        state.data.insert(key.to_owned(), value);
        state.dirty = true;
        Ok(())
    }

    pub fn remove(&self, key: &str) {
        let mut state = self.state();
        if state.data.remove(key).is_some() {
            state.dirty = true;
        }
    }

    /// Removes everything, e.g. on sign-out.
    pub fn clear(&self) {
        let mut state = self.state();
        state.data.clear();
        state.dirty = true;
    }

    /// A flash message set by an earlier request (or `flash_now`). Reading
    /// the flash spends it: the next request won't see these messages.
    pub fn flash(&self, kind: &str) -> Option<String> {
        let mut state = self.state();
        if !state.flash.is_empty() && !state.flash_read {
            state.flash_read = true;
            state.dirty = true;
        }
        state
            .flash
            .get(kind)
            .and_then(Value::as_str)
            .map(str::to_owned)
    }

    /// A flash message for the page this request renders, not the next
    /// one, as Rails' `flash.now`: for a form shown again with an error.
    pub fn flash_now(&self, kind: &str, message: impl Into<String>) {
        self.state()
            .flash
            .insert(kind.to_owned(), Value::String(message.into()));
    }

    /// Sets a flash message for the next request, typically before a redirect.
    pub fn put_flash(&self, kind: &str, message: impl Into<String>) {
        let mut state = self.state();
        let flash = state
            .data
            .entry(FLASH_KEY)
            .or_insert_with(|| Value::Object(Map::new()));
        if let Value::Object(flash) = flash {
            flash.insert(kind.to_owned(), Value::String(message.into()));
        }
        state.flash_set.push(kind.to_owned());
        state.dirty = true;
    }

    /// Writes the session cookie if anything changed.
    pub(crate) fn commit(&self) {
        let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner());
        if !state.loaded || !state.dirty {
            return;
        }
        // A read flash is spent: keep only what this request set.
        if state.flash_read {
            let set = std::mem::take(&mut state.flash_set);
            let kept: Map<String, Value> = match state.data.remove(FLASH_KEY) {
                Some(Value::Object(flash)) => flash
                    .into_iter()
                    .filter(|(kind, _)| set.contains(kind))
                    .collect(),
                _ => Map::new(),
            };
            if !kept.is_empty() {
                state.data.insert(FLASH_KEY.to_owned(), Value::Object(kept));
            }
        }
        if state.data.is_empty() {
            if self.cookies.get(COOKIE_NAME).is_some() {
                self.cookies.remove(COOKIE_NAME);
            }
            return;
        }
        let json = Value::Object(state.data.clone()).to_string();
        self.cookies.add_private(
            Cookie::build((COOKIE_NAME, json))
                .path("/")
                .http_only(true)
                .same_site(SameSite::Lax)
                .secure(self.secure),
        );
    }
}