1
0
mirror of https://github.com/actix/examples synced 2024-11-23 22:41:07 +01:00

updated redis-session with comprehensive example and tests

This commit is contained in:
dowwie 2019-07-11 15:10:09 -04:00
parent 8c019519b9
commit 99c9e145c1
3 changed files with 247 additions and 20 deletions

View File

@ -1,13 +1,18 @@
[package] [package]
name = "redis-session" name = "redis_session_test"
version = "0.1.0" version = "0.1.0"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"] authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
workspace = ".." workspace = ".."
edition = "2018" edition = "2018"
[dependencies] [dependencies]
actix = "0.8.2"
actix-web = "1.0.3" actix-web = "1.0.3"
actix-session = "0.1.0" actix-session = "0.2.0"
actix-redis = { version = "0.6", features = ["web"] } actix-redis = { version = "0.6.0", features = ["web"] }
env_logger = "0.6" env_logger = "0.6"
serde = { version = "^1.0", features = ["derive"] }
actix-service = "0.4.1"
actix-http-test = "0.2.2"
actix-http = "0.2.5"
serde_json = "1.0.40"
time = "0.1.42"

0
redis-session/README.md Normal file
View File

View File

@ -1,23 +1,66 @@
//! Example of redis based session //! Example of login and logout using redis-based sessions
//!
//! Every request gets a session, corresponding to a cache entry and cookie.
//! At login, the session key changes and session state in cache re-assigns.
//! At logout, session state in cache is removed and cookie is invalidated.
//! //!
//! [User guide](https://actix.rs/book/actix-web/sec-9-middlewares.html#user-sessions)
use actix_redis::RedisSession; use actix_redis::RedisSession;
use actix_session::Session; use actix_session::Session;
use actix_web::{middleware, web, App, HttpRequest, HttpResponse, HttpServer, Result}; use actix_web::{middleware, web, App, HttpResponse, HttpServer, Result,
web::{resource, get, post}};
use serde::{Deserialize, Serialize};
/// simple handler
fn index(req: HttpRequest, session: Session) -> Result<HttpResponse> {
println!("{:?}", req);
// session #[derive(Serialize, Deserialize, Debug, PartialEq)]
if let Some(count) = session.get::<i32>("counter")? { pub struct IndexResponse {
println!("SESSION value: {}", count); user_id: Option<String>,
session.set("counter", count + 1)?; counter: i32
} else {
session.set("counter", 1)?;
} }
Ok("Welcome!".into()) fn index(session: Session) -> Result<HttpResponse> {
let user_id: Option<String> = session.get::<String>("user_id").unwrap();
let counter: i32 = session.get::<i32>("counter")
.unwrap_or(Some(0))
.unwrap_or(0);
Ok(HttpResponse::Ok().json(IndexResponse{user_id, counter}))
}
fn do_something(session: Session) -> Result<HttpResponse> {
let user_id: Option<String> = session.get::<String>("user_id").unwrap();
let counter: i32 = session.get::<i32>("counter")
.unwrap_or(Some(0))
.map_or(1, |inner| inner + 1);
session.set("counter", counter)?;
Ok(HttpResponse::Ok().json(IndexResponse{user_id, counter}))
}
#[derive(Deserialize)]
struct Identity {
user_id: String
}
fn login(user_id: web::Json<Identity>, session: Session) -> Result<HttpResponse> {
let id = user_id.into_inner().user_id;
session.set("user_id", &id)?;
session.renew();
let counter: i32 = session.get::<i32>("counter")
.unwrap_or(Some(0))
.unwrap_or(0);
Ok(HttpResponse::Ok().json(IndexResponse{user_id: Some(id), counter}))
}
fn logout(session: Session) -> Result<HttpResponse> {
let id: Option<String> = session.get("user_id")?;
if let Some(x) = id{
session.purge();
Ok(format!("Logged out: {}", x).into())
} else {
Ok("Could not log out anonymous user".into())
}
} }
fn main() -> std::io::Result<()> { fn main() -> std::io::Result<()> {
@ -30,9 +73,188 @@ fn main() -> std::io::Result<()> {
.wrap(RedisSession::new("127.0.0.1:6379", &[0; 32])) .wrap(RedisSession::new("127.0.0.1:6379", &[0; 32]))
// enable logger - always register actix-web Logger middleware last // enable logger - always register actix-web Logger middleware last
.wrap(middleware::Logger::default()) .wrap(middleware::Logger::default())
// register simple route, handle all methods .service(resource("/").route(get().to(index)))
.service(web::resource("/").to(index)) .service(resource("/do_something").route(post().to(do_something)))
.service(resource("/login").route(post().to(login)))
.service(resource("/logout").route(post().to(logout)))
}) })
.bind("127.0.0.1:8080")? .bind("127.0.0.1:8080")?
.run() .run()
} }
#[cfg(test)]
mod test {
use super::*;
use actix_http::{HttpService, httpmessage::HttpMessage};
use actix_http_test::{TestServer, block_on};
use actix_web::{middleware, App, web::{resource, get, post}};
use serde_json::json;
use time;
#[test]
fn test_workflow() {
// Step 1: GET index
// - set-cookie actix-session will be in response (session cookie #1)
// - response should be: {"counter": 0, "user_id": None}
// Step 2: GET index, including session cookie #1 in request
// - set-cookie will *not* be in response
// - response should be: {"counter": 0, "user_id": None}
// Step 3: POST to do_something, including session cookie #1 in request
// - adds new session state in redis: {"counter": 1}
// - response should be: {"counter": 1, "user_id": None}
// Step 4: POST again to do_something, including session cookie #1 in request
// - updates session state in redis: {"counter": 2}
// - response should be: {"counter": 2, "user_id": None}
// Step 5: POST to login, including session cookie #1 in request
// - set-cookie actix-session will be in response (session cookie #2)
// - updates session state in redis: {"counter": 2, "user_id": "ferris"}
// Step 6: GET index, including session cookie #2 in request
// - response should be: {"counter": 2, "user_id": "ferris"}
// Step 7: POST again to do_something, including session cookie #2 in request
// - updates session state in redis: {"counter": 3, "user_id": "ferris"}
// - response should be: {"counter": 2, "user_id": None}
// Step 8: GET index, including session cookie #1 in request
// - set-cookie actix-session will be in response (session cookie #3)
// - response should be: {"counter": 0, "user_id": None}
// Step 9: POST to logout, including session cookie #2
// - set-cookie actix-session will be in response with session cookie #2
// invalidation logic
// Step 10: GET index, including session cookie #2 in request
// - set-cookie actix-session will be in response (session cookie #3)
// - response should be: {"counter": 0, "user_id": None}
let mut srv =
TestServer::new(|| {
HttpService::new(
App::new()
.wrap(RedisSession::new("127.0.0.1:6379", &[0; 32])
.cookie_name("test-session"))
.wrap(middleware::Logger::default())
.service(resource("/").route(get().to(index)))
.service(resource("/do_something").route(post().to(do_something)))
.service(resource("/login").route(post().to(login)))
.service(resource("/logout").route(post().to(logout)))
)
});
// Step 1: GET index
// - set-cookie actix-session will be in response (session cookie #1)
// - response should be: {"counter": 0, "user_id": None}
let req_1a = srv.get("/").send();
let mut resp_1 = srv.block_on(req_1a).unwrap();
let cookie_1 = resp_1.cookies().unwrap().clone()
.into_iter().find(|c| c.name() == "test-session")
.unwrap();
let result_1 = block_on(resp_1.json::<IndexResponse>()).unwrap();
assert_eq!(result_1, IndexResponse{user_id: None, counter: 0});
// Step 2: GET index, including session cookie #1 in request
// - set-cookie will *not* be in response
// - response should be: {"counter": 0, "user_id": None}
let req_2 = srv.get("/").cookie(cookie_1.clone()).send();
let resp_2 = srv.block_on(req_2).unwrap();
let cookie_2 = resp_2.cookies().unwrap().clone()
.into_iter().find(|c| c.name() == "test-session");
assert_eq!(cookie_2, None);
// Step 3: POST to do_something, including session cookie #1 in request
// - adds new session state in redis: {"counter": 1}
// - response should be: {"counter": 1, "user_id": None}
let req_3 = srv.post("/do_something").cookie(cookie_1.clone()).send();
let mut resp_3 = srv.block_on(req_3).unwrap();
let result_3 = block_on(resp_3.json::<IndexResponse>()).unwrap();
assert_eq!(result_3, IndexResponse{user_id: None, counter: 1});
// Step 4: POST again to do_something, including session cookie #1 in request
// - updates session state in redis: {"counter": 2}
// - response should be: {"counter": 2, "user_id": None}
let req_4 = srv.post("/do_something").cookie(cookie_1.clone()).send();
let mut resp_4 = srv.block_on(req_4).unwrap();
let result_4 = block_on(resp_4.json::<IndexResponse>()).unwrap();
assert_eq!(result_4, IndexResponse{user_id: None, counter: 2});
// Step 5: POST to login, including session cookie #1 in request
// - set-cookie actix-session will be in response (session cookie #2)
// - updates session state in redis: {"counter": 2, "user_id": "ferris"}
let req_5 = srv.post("/login")
.cookie(cookie_1.clone())
.send_json(&json!({"user_id": "ferris"}));
let mut resp_5 = srv.block_on(req_5).unwrap();
let cookie_2 = resp_5.cookies().unwrap().clone()
.into_iter().find(|c| c.name() == "test-session")
.unwrap();
assert_eq!(true, cookie_1.value().to_string() != cookie_2.value().to_string());
let result_5 = block_on(resp_5.json::<IndexResponse>()).unwrap();
assert_eq!(result_5, IndexResponse{user_id: Some("ferris".into()), counter: 2});
// Step 6: GET index, including session cookie #2 in request
// - response should be: {"counter": 2, "user_id": "ferris"}
let req_6 = srv.get("/")
.cookie(cookie_2.clone())
.send();
let mut resp_6 = srv.block_on(req_6).unwrap();
let result_6 = block_on(resp_6.json::<IndexResponse>()).unwrap();
assert_eq!(result_6, IndexResponse{user_id: Some("ferris".into()), counter: 2});
// Step 7: POST again to do_something, including session cookie #2 in request
// - updates session state in redis: {"counter": 3, "user_id": "ferris"}
// - response should be: {"counter": 2, "user_id": None}
let req_7 = srv.post("/do_something").cookie(cookie_2.clone()).send();
let mut resp_7 = srv.block_on(req_7).unwrap();
let result_7 = block_on(resp_7.json::<IndexResponse>()).unwrap();
assert_eq!(result_7, IndexResponse{user_id: Some("ferris".into()), counter: 3});
// Step 8: GET index, including session cookie #1 in request
// - set-cookie actix-session will be in response (session cookie #3)
// - response should be: {"counter": 0, "user_id": None}
let req_8 = srv.get("/")
.cookie(cookie_1.clone())
.send();
let mut resp_8 = srv.block_on(req_8).unwrap();
let cookie_3 = resp_8.cookies().unwrap().clone()
.into_iter().find(|c| c.name() == "test-session")
.unwrap();
let result_8 = block_on(resp_8.json::<IndexResponse>()).unwrap();
assert_eq!(result_8, IndexResponse{user_id: None, counter: 0});
assert!(cookie_3.value().to_string() != cookie_2.value().to_string());
// Step 9: POST to logout, including session cookie #2
// - set-cookie actix-session will be in response with session cookie #2
// invalidation logic
let req_9 = srv.post("/logout")
.cookie(cookie_2.clone())
.send();
let resp_9 = srv.block_on(req_9).unwrap();
let cookie_4 = resp_9.cookies().unwrap().clone()
.into_iter().find(|c| c.name() == "test-session")
.unwrap();
assert!(&time::now().tm_year != &cookie_4.expires().map(|t| t.tm_year).unwrap());
// Step 10: GET index, including session cookie #2 in request
// - set-cookie actix-session will be in response (session cookie #3)
// - response should be: {"counter": 0, "user_id": None}
let req_10 = srv.get("/")
.cookie(cookie_2.clone())
.send();
let mut resp_10 = srv.block_on(req_10).unwrap();
let result_10 = block_on(resp_10.json::<IndexResponse>()).unwrap();
assert_eq!(result_10, IndexResponse{user_id: None, counter: 0});
let cookie_5 = resp_10.cookies().unwrap().clone()
.into_iter().find(|c| c.name() == "test-session")
.unwrap();
assert!(cookie_5.value().to_string() != cookie_2.value().to_string());
}
}