1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
use std::{
    collections::BTreeMap,
    convert::Infallible,
    fmt::{self, Debug, Formatter},
    sync::Arc,
};

use parking_lot::RwLock;
use serde::{de::DeserializeOwned, Serialize};

use crate::{FromRequest, Request, RequestBody};

/// Status of the Session.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum SessionStatus {
    /// Indicates that the session state has changed.
    Changed,

    /// Indicates that the session state needs to be cleared.
    Purged,

    /// Indicates that the session TTL(time-to-live) needs to be reset.
    Renewed,

    /// Indicates that the session state is unchanged.
    Unchanged,
}

struct SessionInner {
    status: SessionStatus,
    entries: BTreeMap<String, String>,
}

/// Session
#[derive(Clone)]
pub struct Session {
    inner: Arc<RwLock<SessionInner>>,
}

impl Debug for Session {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        let inner = self.inner.read();
        f.debug_struct("Session")
            .field("status", &inner.status)
            .field("entries", &inner.entries)
            .finish()
    }
}

impl Default for Session {
    fn default() -> Self {
        Self::new(Default::default())
    }
}

impl Session {
    /// Creates a new session instance.
    ///
    /// The default status is [`SessionStatus::Unchanged`].
    pub(crate) fn new(entries: BTreeMap<String, String>) -> Self {
        Self {
            inner: Arc::new(RwLock::new(SessionInner {
                status: SessionStatus::Unchanged,
                entries,
            })),
        }
    }

    /// Get a value from the session.
    pub fn get<T: DeserializeOwned>(&self, name: &str) -> Option<T> {
        let inner = self.inner.read();
        inner
            .entries
            .get(name)
            .and_then(|value| serde_json::from_str(value).ok())
    }

    /// Sets a key-value pair into the session.
    pub fn set(&self, name: &str, value: impl Serialize) {
        let mut inner = self.inner.write();

        if inner.status != SessionStatus::Purged {
            if let Ok(value) = serde_json::to_string(&value) {
                inner.entries.insert(name.to_string(), value);
                inner.status = SessionStatus::Changed;
            }
        }
    }

    /// Remove value from the session.
    pub fn remove(&self, name: &str) {
        let mut inner = self.inner.write();
        if inner.status != SessionStatus::Purged {
            inner.entries.remove(name);
            inner.status = SessionStatus::Changed;
        }
    }

    /// Returns `true` is this session does not contain any values, otherwise it
    /// returns `false`.
    pub fn is_empty(&self) -> bool {
        let inner = self.inner.read();
        inner.entries.is_empty()
    }

    /// Get all raw key-value data from the session
    pub fn entries(&self) -> BTreeMap<String, String> {
        let inner = self.inner.read();
        inner.entries.clone()
    }

    /// Clear the session.
    pub fn clear(&self) {
        let mut inner = self.inner.write();
        if inner.status != SessionStatus::Purged {
            inner.entries.clear();
            inner.status = SessionStatus::Changed;
        }
    }

    /// Renews the session key, assigning existing session state to new key.
    pub fn renew(&self) {
        let mut inner = self.inner.write();
        inner.status = SessionStatus::Renewed;
    }

    /// Removes session both client and server side.
    pub fn purge(&self) {
        let mut inner = self.inner.write();
        if inner.status != SessionStatus::Purged {
            inner.entries.clear();
            inner.status = SessionStatus::Purged;
        }
    }

    /// Returns the status of this session.
    pub fn status(&self) -> SessionStatus {
        let inner = self.inner.read();
        inner.status
    }
}

#[async_trait::async_trait]
impl<'a> FromRequest<'a> for &'a Session {
    type Error = Infallible;

    async fn from_request(req: &'a Request, _body: &mut RequestBody) -> Result<Self, Self::Error> {
        Ok(req
            .extensions()
            .get::<Session>()
            .expect("To use the `Session` extractor, the `CookieSession` middleware is required."))
    }
}