use dustnet_core::session::SessionDirective;
pub trait SessionResolver: Send + Sync {
fn identity(&self, token: &str) -> Option<String>;
fn revoke(&self, token: &str) {
let _ = token;
}
}
pub type Identity = Option<String>;
#[derive(Debug, Clone, Default)]
pub struct SessionChange {
directives: Vec<SessionDirective>,
}
impl SessionChange {
pub fn none() -> Self {
Self::default()
}
pub fn set(token: impl Into<String>, scope: impl Into<String>, expires: u64) -> Self {
Self {
directives: vec![SessionDirective::Set {
token: token.into(),
scope: scope.into(),
expires: Some(expires),
}],
}
}
pub fn clear(scope: impl Into<String>) -> Self {
Self {
directives: vec![SessionDirective::Clear {
scope: scope.into(),
}],
}
}
pub fn is_empty(&self) -> bool {
self.directives.is_empty()
}
pub fn token(&self) -> Option<&str> {
self.directives
.iter()
.find_map(|directive| match directive {
SessionDirective::Set { token, .. } => Some(token.as_str()),
SessionDirective::Clear { .. } => None,
})
}
pub(crate) fn clears(&self) -> bool {
self.directives
.iter()
.any(|directive| matches!(directive, SessionDirective::Clear { .. }))
}
pub(crate) fn into_directives(self) -> Vec<SessionDirective> {
self.directives
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_set_carries_its_scope_and_expiry() {
let change = SessionChange::set("abc", "/", 1_800_000_000);
let directives = change.into_directives();
assert_eq!(directives.len(), 1);
match &directives[0] {
SessionDirective::Set {
token,
scope,
expires,
} => {
assert_eq!(token, "abc");
assert_eq!(scope, "/");
assert_eq!(*expires, Some(1_800_000_000));
}
other => panic!("expected Set, got {other:?}"),
}
}
#[test]
fn a_clear_names_only_its_scope() {
match &SessionChange::clear("/").into_directives()[0] {
SessionDirective::Clear { scope } => assert_eq!(scope, "/"),
other => panic!("expected Clear, got {other:?}"),
}
}
#[test]
fn the_issued_token_is_readable_and_a_clear_has_none() {
assert_eq!(SessionChange::set("abc", "/", 1).token(), Some("abc"));
assert_eq!(SessionChange::clear("/").token(), None);
assert_eq!(SessionChange::none().token(), None);
}
#[test]
fn only_a_clear_asks_for_revocation() {
assert!(SessionChange::clear("/").clears());
assert!(!SessionChange::set("t", "/", 1).clears());
assert!(!SessionChange::none().clears());
}
#[test]
fn no_change_is_empty() {
assert!(SessionChange::none().is_empty());
assert!(SessionChange::none().into_directives().is_empty());
}
#[test]
fn issued_directives_serialize() {
for change in [
SessionChange::set("a".repeat(64), "/", 1_800_000_000),
SessionChange::clear("/"),
] {
for directive in change.into_directives() {
directive.serialize().expect("directive serializes");
}
}
}
}