Skip to main content

doido_cable/
connection.rs

1//! Cable connection identity + authorization (Rails `identified_by` /
2//! `reject_unauthorized_connection`).
3//!
4//! A connection carries named identifiers (e.g. `current_user`) and is rejected
5//! until it is authorized (e.g. after verifying a token in `connect`).
6
7use std::collections::BTreeMap;
8
9/// The identity of one WebSocket connection.
10#[derive(Debug, Default, Clone)]
11pub struct CableConnection {
12    identifiers: BTreeMap<String, String>,
13    authorized: bool,
14}
15
16impl CableConnection {
17    pub fn new() -> Self {
18        Self::default()
19    }
20
21    /// Attach an identifier (Rails `self.current_user = ...`).
22    pub fn identify(&mut self, key: &str, value: &str) -> &mut Self {
23        self.identifiers.insert(key.to_string(), value.to_string());
24        self
25    }
26
27    /// Read an identifier.
28    pub fn identifier(&self, key: &str) -> Option<&str> {
29        self.identifiers.get(key).map(String::as_str)
30    }
31
32    /// Mark the connection authorized (accept it).
33    pub fn authorize(&mut self) -> &mut Self {
34        self.authorized = true;
35        self
36    }
37
38    /// Reject the connection (Rails `reject_unauthorized_connection`).
39    pub fn reject(&mut self) -> &mut Self {
40        self.authorized = false;
41        self
42    }
43
44    /// Whether the connection has been authorized.
45    pub fn is_authorized(&self) -> bool {
46        self.authorized
47    }
48}