1
0
mirror of https://github.com/actix/examples synced 2024-12-05 03:01:55 +01:00
examples/auth/redis-session/src/main.rs

289 lines
9.9 KiB
Rust
Raw Normal View History

//! 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.
2018-05-03 00:11:57 +02:00
//!
use actix_session::{storage::RedisActorSessionStore, Session, SessionMiddleware};
2019-07-18 14:03:19 +02:00
use actix_web::{
middleware, web,
web::{get, post, resource},
App, HttpResponse, HttpServer, Result,
};
use serde::{Deserialize, Serialize};
2022-07-09 22:05:06 +02:00
#[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
pub struct IndexResponse {
user_id: Option<String>,
2019-07-18 14:03:19 +02:00
counter: i32,
}
2019-12-16 06:23:36 +01:00
async fn index(session: Session) -> Result<HttpResponse> {
let user_id: Option<String> = session.get::<String>("user_id").unwrap();
2019-07-18 14:03:19 +02:00
let counter: i32 = session
.get::<i32>("counter")
.unwrap_or(Some(0))
.unwrap_or(0);
2019-07-18 14:03:19 +02:00
Ok(HttpResponse::Ok().json(IndexResponse { user_id, counter }))
}
2019-12-16 06:23:36 +01:00
async fn do_something(session: Session) -> Result<HttpResponse> {
let user_id: Option<String> = session.get::<String>("user_id").unwrap();
2019-07-18 14:03:19 +02:00
let counter: i32 = session
.get::<i32>("counter")
.unwrap_or(Some(0))
.map_or(1, |inner| inner + 1);
session.insert("counter", counter)?;
2019-07-18 14:03:19 +02:00
Ok(HttpResponse::Ok().json(IndexResponse { user_id, counter }))
}
#[derive(Deserialize)]
struct Identity {
2019-07-18 14:03:19 +02:00
user_id: String,
}
2019-12-16 06:23:36 +01:00
async fn login(user_id: web::Json<Identity>, session: Session) -> Result<HttpResponse> {
let id = user_id.into_inner().user_id;
session.insert("user_id", &id)?;
session.renew();
2019-07-18 14:03:19 +02:00
let counter: i32 = session
.get::<i32>("counter")
.unwrap_or(Some(0))
.unwrap_or(0);
2019-07-18 14:03:19 +02:00
Ok(HttpResponse::Ok().json(IndexResponse {
user_id: Some(id),
counter,
}))
}
async fn logout(session: Session) -> Result<String> {
let id: Option<String> = session.get("user_id")?;
2019-07-18 14:03:19 +02:00
if let Some(x) = id {
session.purge();
Ok(format!("Logged out: {x}"))
} else {
Ok("Could not log out anonymous user".into())
}
}
2020-09-12 17:49:45 +02:00
#[actix_web::main]
2019-12-16 06:23:36 +01:00
async fn main() -> std::io::Result<()> {
2022-03-06 01:41:32 +01:00
env_logger::init_from_env(env_logger::Env::new().default_filter_or("info"));
2022-03-07 14:34:59 +01:00
log::info!("starting HTTP server at http://localhost:8080");
// Generate a random 32 byte key. Note that it is important to use a unique
// private key for every project. Anyone with access to the key can generate
// authentication cookies for any user!
let private_key = actix_web::cookie::Key::generate();
HttpServer::new(move || {
2018-05-03 00:11:57 +02:00
App::new()
// redis session middleware
.wrap(
SessionMiddleware::builder(
RedisActorSessionStore::new("127.0.0.1:6379"),
private_key.clone(),
)
.build(),
)
2022-02-06 09:13:24 +01:00
// enable logger - always register Actix Web Logger middleware last
.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)))
2019-03-10 03:03:09 +01:00
})
2022-02-17 21:22:36 +01:00
.bind(("127.0.0.1", 8080))?
2019-12-25 17:48:33 +01:00
.run()
2019-12-16 06:23:36 +01:00
.await
}
#[cfg(test)]
mod test {
2019-07-18 14:03:19 +02:00
use actix_web::{
middleware,
2019-07-18 14:03:19 +02:00
web::{get, post, resource},
App,
};
use serde_json::json;
2022-07-09 22:08:11 +02:00
use super::*;
#[actix_web::test]
2019-12-16 06:23:36 +01:00
async fn test_workflow() {
let private_key = actix_web::cookie::Key::generate();
let srv = actix_test::start(move || {
2019-12-16 06:23:36 +01:00
App::new()
.wrap(
SessionMiddleware::builder(
RedisActorSessionStore::new("127.0.0.1:6379"),
private_key.clone(),
)
2023-07-09 04:32:47 +02:00
.cookie_name("test-session".to_owned())
.build(),
2019-12-16 06:23:36 +01:00
)
.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)))
2019-07-18 14:03:19 +02:00
});
// Step 1: GET index
2022-02-06 10:04:43 +01:00
// - set-cookie actix-session should NOT be in response (session data is empty)
// - response should be: {"counter": 0, "user_id": None}
let request = srv.get("/").send();
let mut resp_1 = request.await.unwrap();
2022-02-06 10:04:43 +01:00
assert!(resp_1.cookies().unwrap().is_empty());
2019-12-16 06:23:36 +01:00
let result_1 = resp_1.json::<IndexResponse>().await.unwrap();
2019-07-18 14:03:19 +02:00
assert_eq!(
result_1,
IndexResponse {
user_id: None,
counter: 0
}
);
2022-02-06 10:04:43 +01:00
// Step 2: 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").send();
let mut resp_3 = req_3.await.unwrap();
let cookie_1 = resp_3
2019-07-18 14:03:19 +02:00
.cookies()
.unwrap()
.clone()
.into_iter()
2022-02-06 10:04:43 +01:00
.find(|c| c.name() == "test-session")
.unwrap();
2019-12-16 06:23:36 +01:00
let result_3 = resp_3.json::<IndexResponse>().await.unwrap();
2019-07-18 14:03:19 +02:00
assert_eq!(
result_3,
IndexResponse {
user_id: None,
counter: 1
}
);
2022-02-06 10:04:43 +01:00
// Step 3: POST again to do_something, including session cookie #1 in request
2019-07-18 14:03:19 +02:00
// - 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();
2019-12-16 06:23:36 +01:00
let mut resp_4 = req_4.await.unwrap();
let result_4 = resp_4.json::<IndexResponse>().await.unwrap();
2019-07-18 14:03:19 +02:00
assert_eq!(
result_4,
IndexResponse {
user_id: None,
counter: 2
}
);
2022-02-06 10:04:43 +01:00
// Step 4: 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"}
2019-07-18 14:03:19 +02:00
let req_5 = srv
.post("/login")
.cookie(cookie_1.clone())
.send_json(&json!({"user_id": "ferris"}));
2019-12-16 06:23:36 +01:00
let mut resp_5 = req_5.await.unwrap();
2019-07-18 14:03:19 +02:00
let cookie_2 = resp_5
.cookies()
.unwrap()
.clone()
.into_iter()
.find(|c| c.name() == "test-session")
.unwrap();
2020-09-16 02:11:49 +02:00
assert_ne!(cookie_1.value(), cookie_2.value());
2019-12-16 06:23:36 +01:00
let result_5 = resp_5.json::<IndexResponse>().await.unwrap();
2019-07-18 14:03:19 +02:00
assert_eq!(
result_5,
IndexResponse {
user_id: Some("ferris".into()),
counter: 2
}
);
2022-02-06 10:04:43 +01:00
// Step 5: GET index, including session cookie #2 in request
// - response should be: {"counter": 2, "user_id": "ferris"}
2019-07-18 14:03:19 +02:00
let req_6 = srv.get("/").cookie(cookie_2.clone()).send();
2019-12-16 06:23:36 +01:00
let mut resp_6 = req_6.await.unwrap();
let result_6 = resp_6.json::<IndexResponse>().await.unwrap();
2019-07-18 14:03:19 +02:00
assert_eq!(
result_6,
IndexResponse {
user_id: Some("ferris".into()),
counter: 2
}
);
2022-02-06 10:04:43 +01:00
// Step 6: 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();
2019-12-16 06:23:36 +01:00
let mut resp_7 = req_7.await.unwrap();
let result_7 = resp_7.json::<IndexResponse>().await.unwrap();
2019-07-18 14:03:19 +02:00
assert_eq!(
result_7,
IndexResponse {
user_id: Some("ferris".into()),
counter: 3
}
);
2022-02-06 10:04:43 +01:00
// Step 7: 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}
2019-07-18 14:03:19 +02:00
let req_8 = srv.get("/").cookie(cookie_1.clone()).send();
2019-12-16 06:23:36 +01:00
let mut resp_8 = req_8.await.unwrap();
2022-02-06 10:04:43 +01:00
assert!(resp_8.cookies().unwrap().is_empty());
2019-12-16 06:23:36 +01:00
let result_8 = resp_8.json::<IndexResponse>().await.unwrap();
2019-07-18 14:03:19 +02:00
assert_eq!(
result_8,
IndexResponse {
user_id: None,
counter: 0
}
);
2022-02-06 10:04:43 +01:00
// Step 8: POST to logout, including session cookie #2
// - set-cookie actix-session will be in response with session cookie #2
// invalidation logic
2019-07-18 14:03:19 +02:00
let req_9 = srv.post("/logout").cookie(cookie_2.clone()).send();
2019-12-16 06:23:36 +01:00
let resp_9 = req_9.await.unwrap();
2019-07-18 14:03:19 +02:00
let cookie_4 = resp_9
.cookies()
.unwrap()
.clone()
.into_iter()
.find(|c| c.name() == "test-session")
.unwrap();
2020-09-12 17:49:45 +02:00
let now = time::OffsetDateTime::now_utc();
assert_ne!(
2022-02-02 16:50:58 +01:00
now.year(),
cookie_4.expires().unwrap().datetime().unwrap().year()
);
2022-02-06 10:04:43 +01:00
// Step 9: 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}
2019-07-18 14:03:19 +02:00
let req_10 = srv.get("/").cookie(cookie_2.clone()).send();
2019-12-16 06:23:36 +01:00
let mut resp_10 = req_10.await.unwrap();
let result_10 = resp_10.json::<IndexResponse>().await.unwrap();
2019-07-18 14:03:19 +02:00
assert_eq!(
result_10,
IndexResponse {
user_id: None,
counter: 0
}
);
}
2019-07-18 14:03:19 +02:00
}