Skip to main content

livewire/
session.rs

1//! The session access the server half needs synchronously, and the keys session-backed properties
2//! persist under.
3
4use laravel::session::Session;
5use laravel_core::context::Context;
6use laravel_http::session::SessionInternals as _;
7use serde_json::Value;
8
9/// The session of the request being handled, or `None` on a route without one.
10///
11/// Component templates read the CSRF token and session-backed properties synchronously, because
12/// MiniJinja's rendering is synchronous.
13#[must_use]
14pub fn current() -> Option<Session> {
15    Session::of(&Context::current()?)
16}
17
18/// The request's CSRF token, or `None` on a route without a session.
19#[must_use]
20pub fn csrf_token() -> Option<String> {
21    current().map(|session| session.token())
22}
23
24/// Reads a value a session-backed property persisted, or `None` when the session has none.
25#[must_use]
26pub fn get(key: &str) -> Option<Value> {
27    current()?.get::<Value>(key)
28}
29
30/// Writes a value a session-backed property persists.
31///
32/// Returns `false` when the route has no session, so the caller can skip the write instead of
33/// panicking in the middle of a render.
34pub fn put(key: &str, value: &Value) -> bool {
35    match current() {
36        Some(session) => {
37            session.put(key, value);
38            true
39        }
40        None => false,
41    }
42}
43
44/// Forgets a value, such as one that no longer fits its property.
45pub fn forget(key: &str) -> bool {
46    match current() {
47        Some(session) => {
48            session.forget(key);
49            true
50        }
51        None => false,
52    }
53}
54
55/// Whether the session holds a value for the key.
56#[must_use]
57pub fn exists(key: &str) -> bool {
58    current().is_some_and(|session| session.exists(key))
59}
60
61/// The key a session-backed property persists under.
62///
63/// A property with a configured key uses it, with `{path}` placeholders replaced from `lookup`.
64/// A property without one uses `lw{crc32}`, so two components with a property of the same name do
65/// not share a value.
66#[must_use]
67pub fn property_key(
68    component: &str,
69    property: &str,
70    configured: Option<&str>,
71    lookup: impl Fn(&str) -> Option<String>,
72) -> String {
73    match configured {
74        Some(key) => replace_placeholders(key, lookup),
75        None => {
76            let mut name = String::with_capacity(component.len() + property.len());
77            name.push_str(component);
78            name.push_str(property);
79
80            format!("lw{}", crc32(name.as_bytes()))
81        }
82    }
83}
84
85/// Replaces every `{path}` in a configured session key with the component value it names.
86///
87/// A placeholder that names nothing is left as it was, so a key never loses its identity.
88fn replace_placeholders(key: &str, lookup: impl Fn(&str) -> Option<String>) -> String {
89    let mut out = String::with_capacity(key.len());
90    let mut rest = key;
91
92    while let Some(start) = rest.find('{') {
93        let Some(end) = rest[start..].find('}').map(|end| start + end) else {
94            break;
95        };
96        out.push_str(&rest[..start]);
97        let path = &rest[start + 1..end];
98        match lookup(path) {
99            Some(value) => out.push_str(&value),
100            None => out.push_str(&rest[start..=end]),
101        }
102        rest = &rest[end + 1..];
103    }
104
105    out.push_str(rest);
106    out
107}
108
109/// The CRC-32 (IEEE 802.3) checksum of `bytes`, as PHP's `crc32()` and zlib compute it.
110#[must_use]
111pub fn crc32(bytes: &[u8]) -> u32 {
112    let mut crc = 0xffff_ffffu32;
113
114    for &byte in bytes {
115        crc ^= u32::from(byte);
116        for _ in 0..8 {
117            let mask = (crc & 1).wrapping_neg();
118            crc = (crc >> 1) ^ (0xedb8_8320 & mask);
119        }
120    }
121
122    !crc
123}
124
125#[cfg(test)]
126mod tests {
127    use super::*;
128
129    #[test]
130    fn crc32_matches_the_standard_check_value() {
131        assert_eq!(crc32(b"123456789"), 0xcbf4_3926);
132        assert_eq!(crc32(b""), 0);
133        assert_eq!(crc32(b"The quick brown fox jumps over the lazy dog"), 0x414f_a339);
134    }
135
136    #[test]
137    fn a_property_without_a_key_is_scoped_to_its_component() {
138        let counter = property_key("counter", "step", None, |_| None);
139        let other = property_key("timer", "step", None, |_| None);
140
141        assert!(counter.starts_with("lw"));
142        assert_ne!(counter, other);
143        // Stable across calls, so a value persisted last request is found again.
144        assert_eq!(counter, property_key("counter", "step", None, |_| None));
145    }
146
147    #[test]
148    fn a_configured_key_replaces_its_placeholders() {
149        let key = property_key("counter", "step", Some("cart-{id}-{user.id}"), |path| match path {
150            "id" => Some("7".to_owned()),
151            "user.id" => Some("42".to_owned()),
152            _ => None,
153        });
154
155        assert_eq!(key, "cart-7-42");
156    }
157
158    #[test]
159    fn an_unknown_placeholder_keeps_its_text() {
160        let key = property_key("counter", "step", Some("cart-{missing}"), |_| None);
161
162        assert_eq!(key, "cart-{missing}");
163    }
164
165    #[test]
166    fn a_configured_key_without_placeholders_is_used_as_it_is() {
167        assert_eq!(
168            property_key("counter", "step", Some("component-key"), |_| None),
169            "component-key"
170        );
171    }
172}