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
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
#![doc = include_str!("../README.md")]
#![warn(missing_docs)]
#[cfg(test)]
mod test;
pub mod memory;
#[cfg(feature = "redis")]
pub mod redis;
use std::time::Duration;
use rand::{
rngs::OsRng,
Rng,
};
use rocket::{
fairing::{
Fairing,
Info,
Kind,
},
http::{
Cookie,
Status,
},
request::{
FromRequest,
Outcome,
},
response::Responder,
tokio::sync::Mutex,
Build,
Request,
Response,
Rocket,
State,
};
use thiserror::Error;
fn new_id(length: usize) -> String {
OsRng
.sample_iter(&rand::distributions::Alphanumeric)
.take(length)
.map(char::from)
.collect()
}
const ID_LENGTH: usize = 24;
#[rocket::async_trait]
pub trait Store: Send + Sync {
type Value;
async fn get(&self, id: &str) -> SessionResult<Option<Self::Value>>;
async fn set(&self, id: &str, value: Self::Value, duration: Duration) -> SessionResult<()>;
async fn touch(&self, id: &str, duration: Duration) -> SessionResult<()>;
async fn remove(&self, id: &str) -> SessionResult<()>;
}
#[derive(Debug, Clone)]
struct SessionID(String);
impl AsRef<str> for SessionID {
fn as_ref(&self) -> &str {
&self.0
}
}
pub struct Session<'s, T: 'static> {
store: &'s State<SessionStore<T>>,
pub(crate) token: SessionID,
}
impl<'s, T> Session<'s, T> {
pub async fn get(&self) -> SessionResult<Option<T>> {
self.store.store.get(self.token.as_ref()).await
}
pub async fn set(&self, value: T) -> SessionResult<()> {
self.store
.store
.set(self.token.as_ref(), value, self.store.duration)
.await
}
pub async fn touch(&self) -> SessionResult<()> {
self.store
.store
.touch(self.token.as_ref(), self.store.duration)
.await
}
pub async fn remove(&self) -> SessionResult<()> {
self.store.store.remove(self.token.as_ref()).await
}
}
#[rocket::async_trait]
impl<T, 'r, 's> FromRequest<'r> for Session<'s, T>
where
T: Send + Sync + 'static + Clone,
'r: 's,
{
type Error = ();
async fn from_request(request: &'r Request<'_>) -> Outcome<Self, Self::Error> {
let store: &State<SessionStore<T>> = request
.guard()
.await
.expect("Session store must be set in fairing");
let token: SessionID = request
.local_cache_async(async {
let cookies = request.cookies();
let token = cookies.get(store.name.as_str()).map_or_else(
|| SessionID(new_id(ID_LENGTH)),
|c| SessionID(String::from(c.value())),
);
token
})
.await
.clone();
let session = Session { store, token };
Outcome::Success(session)
}
}
pub struct SessionStore<T> {
pub store: Box<dyn Store<Value = T>>,
pub name: String,
pub duration: Duration,
}
impl<T> SessionStore<T> {
pub fn fairing(self) -> SessionStoreFairing<T> {
SessionStoreFairing {
store: Mutex::new(Some(self)),
}
}
}
pub struct SessionStoreFairing<T> {
store: Mutex<Option<SessionStore<T>>>,
}
#[rocket::async_trait]
impl<T> Fairing for SessionStoreFairing<T>
where
T: 'static,
{
fn info(&self) -> rocket::fairing::Info {
Info {
name: "Session Store",
kind: Kind::Ignite | Kind::Response | Kind::Singleton,
}
}
async fn on_ignite(&self, rocket: Rocket<Build>) -> Result<Rocket<Build>, Rocket<Build>> {
let mut lock = self.store.lock().await;
let store = lock.take().expect("Expected store");
let rocket = rocket.manage(store);
Ok(rocket)
}
async fn on_response<'r>(&self, request: &'r Request<'_>, response: &mut Response<'r>) {
let session: &SessionID = request.local_cache(|| SessionID("".into()));
if !session.0.is_empty() {
let store: &State<SessionStore<T>> = request.guard().await.expect("");
let name = store.name.as_str();
response.adjoin_header(
Cookie::build(name, session.0.as_str())
.http_only(true)
.finish(),
)
}
}
}
pub type SessionResult<T> = Result<T, SessionError>;
#[derive(Error, Debug)]
#[error("could not access the session store")]
pub struct SessionError;
impl<'r, 'o: 'r> Responder<'r, 'o> for SessionError {
fn respond_to(self, _request: &'r Request<'_>) -> rocket::response::Result<'o> {
Err(Status::InternalServerError)
}
}