-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathredis-tide.rs
247 lines (213 loc) · 8.47 KB
/
redis-tide.rs
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
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
use async_std::{prelude::*, task};
use cookie::Cookie;
use futures::future::BoxFuture;
use log::info;
use redis::Client as RedisClient;
use serde::{Deserialize, Serialize};
use sessions::{RedisStore, Session, SessionStatus, Storable};
use std::{convert::TryInto, str::FromStr, sync::Arc};
use tide::{self, Middleware, Next, Request, Response};
use time::Duration;
static SESSION_NAME: &str = "session.id";
#[derive(Debug, Serialize, Deserialize, PartialEq)]
struct User {
logged_in: bool,
count: u32,
}
#[derive(Debug, Clone)]
struct SessionsMiddleware {
store: Arc<RedisStore>,
}
impl Default for SessionsMiddleware {
fn default() -> Self {
Self {
store: Arc::default(),
}
}
}
impl SessionsMiddleware {
/// Creates a new SessionsMiddleware.
pub fn new(store: Arc<RedisStore>) -> Self {
Self { store }
}
}
impl<State: Send + Sync + 'static> Middleware<State> for SessionsMiddleware {
fn handle<'a>(
&'a self,
mut ctx: Request<State>,
next: Next<'a, State>,
) -> BoxFuture<'a, Response> {
Box::pin(async move {
let sid = ctx
.cookie(SESSION_NAME)
.map(|c| c.value().to_owned())
.filter(|id| id.len() == 32)
.unwrap_or_else(|| "".to_owned());
ctx = ctx.set_local(self.store.get(&sid).await);
next.run(ctx).await
})
}
}
trait RequestExt {
fn session(&self) -> &Session;
}
impl<State: Send + Sync + 'static> RequestExt for Request<State> {
fn session(&self) -> &Session {
self.local::<Session>().unwrap()
}
}
#[test]
fn tide_with_redis() -> Result<(), surf::Exception> {
pretty_env_logger::init();
#[derive(Deserialize, Serialize)]
struct Counter {
count: usize,
}
let arc_store = Arc::new(RedisStore::new(
RedisClient::open("redis://127.0.0.1/").unwrap(),
"session:id:",
60 * 5,
));
let store_0 = arc_store.clone();
let store_1 = arc_store.clone();
task::block_on(async {
let server = task::spawn(async move {
let mut app = tide::new();
app.middleware(SessionsMiddleware::new(store_0));
app.at("/").get(|req: tide::Request<()>| async move {
let session = req.session();
if session.status().await == SessionStatus::Existed {
let count = session.get::<usize>("count").await.unwrap_or_else(|| 0) + 1;
session.set("count", count).await;
session.save().await;
info!("User is logged in, {}.", count);
tide::Response::new(200)
.body_json(&session.state().await)
.unwrap()
} else {
info!("User is not logged in.");
tide::Response::new(200).body_string("".to_owned())
}
});
app.at("/session")
.post(|req: tide::Request<()>| async move {
let session = req.session();
let mut count = session.get::<usize>("count").await.unwrap_or_else(|| 0);
let mut res = tide::Response::new(200);
if session.status().await == SessionStatus::Existed {
count += 1;
session.set("count", count).await;
session.save().await;
info!("User is logged in, {}.", count);
} else {
session.set("logged_in", true).await;
session.set("count", count).await;
session.save().await;
info!("User is logged in, {}.", count);
res.set_cookie(Cookie::new(SESSION_NAME, session.id().await));
}
res.body_json(&session.state().await).unwrap()
});
app.at("/logout").post(|req: tide::Request<()>| async move {
let session = req.session();
if session.status().await == SessionStatus::Existed {
let count = session.get::<usize>("count").await.unwrap_or_else(|| 0) + 1;
info!("User is logged in, {}.", count);
session.set("count", count).await;
info!("Session is destroyed.");
session.destroy().await;
let cookie = Cookie::build(SESSION_NAME, session.id().await)
.max_age(Duration::seconds(-1))
.finish();
let mut res = tide::Response::new(200);
res.set_cookie(cookie);
res.body_json(&session.state().await).unwrap()
} else {
info!("Session is not found.");
tide::Response::new(403)
}
});
app.listen("localhost:8082").await?;
Result::<(), surf::Exception>::Ok(())
});
let client = task::spawn(async move {
task::sleep(Duration::milliseconds(100).try_into()?).await;
// First visit home
let mut res = surf::get("http://localhost:8082").await?;
let buf = res.body_bytes().await?;
assert_eq!(res.status(), 200);
assert!(buf.is_empty());
// First login
let mut res = surf::post("http://localhost:8082/session").await?;
assert_eq!(res.status(), 200);
let session_cookie = Cookie::from_str(res.header("SET-COOKIE").unwrap_or_else(|| ""))?;
let sid = session_cookie.value();
assert_eq!(sid.len(), 32);
let user: User = res.body_json().await?;
assert_eq!(true, user.logged_in);
assert_eq!(0, user.count);
let session = store_1.get(sid).await;
assert_eq!(session.status().await, SessionStatus::Existed);
assert_eq!(
serde_json::to_value(user)?
.as_object()
.map(|m| m.to_owned())
.unwrap(),
session.state().await
);
// Second Login.
let mut res = surf::post("http://localhost:8082/session")
.set_header("COOKIE", format!("{}={}", SESSION_NAME, sid))
.await?;
assert_eq!(res.status(), 200);
let user: User = res.body_json().await?;
assert_eq!(true, user.logged_in);
assert_eq!(1, user.count);
let session = store_1.get(sid).await;
assert_eq!(session.status().await, SessionStatus::Existed);
assert_eq!(
serde_json::to_value(user)?
.as_object()
.map(|m| m.to_owned())
.unwrap(),
session.state().await
);
// Second visit home.
let mut res = surf::post("http://localhost:8082/session")
.set_header("COOKIE", format!("{}={}", SESSION_NAME, sid))
.await?;
assert_eq!(res.status(), 200);
let user: User = res.body_json().await?;
assert_eq!(true, user.logged_in);
assert_eq!(2, user.count);
let session = store_1.get(sid).await;
assert_eq!(session.status().await, SessionStatus::Existed);
assert_eq!(
serde_json::to_value(user)?
.as_object()
.map(|m| m.to_owned())
.unwrap(),
session.state().await
);
// First logout.
let mut res = surf::post("http://localhost:8082/logout")
.set_header("COOKIE", format!("{}={}", SESSION_NAME, sid))
.await?;
assert_eq!(res.status(), 200);
assert_eq!(res.body_string().await?, "{}");
// Second logout.
let mut res = surf::post("http://localhost:8082/logout")
.set_header("COOKIE", format!("{}={}", SESSION_NAME, sid))
.await?;
assert_eq!(res.status(), 403);
assert_eq!(res.body_string().await?, "");
// Three visit home.
let mut res = surf::get("http://localhost:8082").await?;
let buf = res.body_bytes().await?;
assert_eq!(res.status(), 200);
assert!(buf.is_empty());
Ok(())
});
server.race(client).await
})
}