Files
axum/examples/sessions/src/main.rs
T

163 lines
4.7 KiB
Rust
Raw Normal View History

2021-08-02 23:09:09 +02:00
//! Run with
//!
//! ```not_rust
2022-04-29 18:53:41 +02:00
//! cd examples && cargo run -p example-sessions
2021-08-02 23:09:09 +02:00
//! ```
2021-08-01 09:15:44 +02:00
use async_session::{MemoryStore, Session, SessionStore as _};
use axum::{
async_trait,
2021-12-22 22:27:13 +08:00
extract::{Extension, FromRequest, RequestParts, TypedHeader},
headers::Cookie,
http::{
self,
header::{HeaderMap, HeaderValue},
StatusCode,
},
2021-08-01 09:15:44 +02:00
response::IntoResponse,
routing::get,
2022-03-01 00:39:22 +01:00
Router,
2021-08-01 09:15:44 +02:00
};
use serde::{Deserialize, Serialize};
2021-12-22 22:27:13 +08:00
use std::fmt::Debug;
2021-08-01 09:15:44 +02:00
use std::net::SocketAddr;
2022-03-06 12:37:00 +01:00
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};
2021-08-01 09:15:44 +02:00
use uuid::Uuid;
2021-12-22 22:27:13 +08:00
const AXUM_SESSION_COOKIE_NAME: &str = "axum_session";
2021-08-01 09:15:44 +02:00
#[tokio::main]
async fn main() {
2022-03-06 12:37:00 +01:00
tracing_subscriber::registry()
.with(tracing_subscriber::EnvFilter::new(
std::env::var("RUST_LOG").unwrap_or_else(|_| "example_sessions=debug".into()),
))
.with(tracing_subscriber::fmt::layer())
.init();
2021-08-01 09:15:44 +02:00
// `MemoryStore` just used as an example. Don't use this in production.
let store = MemoryStore::new();
let app = Router::new()
.route("/", get(handler))
2022-03-01 00:39:22 +01:00
.layer(Extension(store));
2021-08-01 09:15:44 +02:00
let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
tracing::debug!("listening on {}", addr);
axum::Server::bind(&addr)
2021-08-01 09:15:44 +02:00
.serve(app.into_make_service())
.await
.unwrap();
}
async fn handler(user_id: UserIdFromSession) -> impl IntoResponse {
2021-12-22 22:27:13 +08:00
let (headers, user_id, create_cookie) = match user_id {
UserIdFromSession::FoundUserId(user_id) => (HeaderMap::new(), user_id, false),
UserIdFromSession::CreatedFreshUserId(new_user) => {
2021-08-01 09:15:44 +02:00
let mut headers = HeaderMap::new();
2021-12-22 22:27:13 +08:00
headers.insert(http::header::SET_COOKIE, new_user.cookie);
(headers, new_user.user_id, true)
2021-08-01 09:15:44 +02:00
}
};
2021-12-22 22:27:13 +08:00
tracing::debug!("handler: user_id={:?} send_headers={:?}", user_id, headers);
(
headers,
format!(
"user_id={:?} session_cookie_name={} create_new_session_cookie={}",
user_id, AXUM_SESSION_COOKIE_NAME, create_cookie
),
)
}
2021-08-01 09:15:44 +02:00
2021-12-22 22:27:13 +08:00
struct FreshUserId {
pub user_id: UserId,
pub cookie: HeaderValue,
2021-08-01 09:15:44 +02:00
}
enum UserIdFromSession {
FoundUserId(UserId),
2021-12-22 22:27:13 +08:00
CreatedFreshUserId(FreshUserId),
2021-08-01 09:15:44 +02:00
}
#[async_trait]
impl<B> FromRequest<B> for UserIdFromSession
where
B: Send,
{
type Rejection = (StatusCode, &'static str);
async fn from_request(req: &mut RequestParts<B>) -> Result<Self, Self::Rejection> {
2021-08-18 00:04:15 +02:00
let Extension(store) = Extension::<MemoryStore>::from_request(req)
2021-08-01 09:15:44 +02:00
.await
.expect("`MemoryStore` extension missing");
2021-12-22 22:27:13 +08:00
let cookie = Option::<TypedHeader<Cookie>>::from_request(req)
.await
.unwrap();
2021-08-01 09:15:44 +02:00
2021-12-22 22:27:13 +08:00
let session_cookie = cookie
.as_ref()
.and_then(|cookie| cookie.get(AXUM_SESSION_COOKIE_NAME));
// return the new created session cookie for client
if session_cookie.is_none() {
2021-08-01 09:15:44 +02:00
let user_id = UserId::new();
let mut session = Session::new();
session.insert("user_id", user_id).unwrap();
let cookie = store.store_session(session).await.unwrap().unwrap();
2021-12-22 22:27:13 +08:00
return Ok(Self::CreatedFreshUserId(FreshUserId {
2021-08-01 09:15:44 +02:00
user_id,
2021-12-22 22:27:13 +08:00
cookie: HeaderValue::from_str(
format!("{}={}", AXUM_SESSION_COOKIE_NAME, cookie).as_str(),
)
.unwrap(),
}));
}
2021-08-01 09:15:44 +02:00
2021-12-22 22:27:13 +08:00
tracing::debug!(
"UserIdFromSession: got session cookie from user agent, {}={}",
AXUM_SESSION_COOKIE_NAME,
session_cookie.unwrap()
);
// continue to decode the session cookie
let user_id = if let Some(session) = store
.load_session(session_cookie.unwrap().to_owned())
.await
.unwrap()
{
2021-08-01 09:15:44 +02:00
if let Some(user_id) = session.get::<UserId>("user_id") {
2021-12-22 22:27:13 +08:00
tracing::debug!(
"UserIdFromSession: session decoded success, user_id={:?}",
user_id
);
2021-08-01 09:15:44 +02:00
user_id
} else {
return Err((
StatusCode::INTERNAL_SERVER_ERROR,
"No `user_id` found in session",
));
}
} else {
2021-12-22 22:27:13 +08:00
tracing::debug!(
"UserIdFromSession: err session not exists in store, {}={}",
AXUM_SESSION_COOKIE_NAME,
session_cookie.unwrap()
);
2021-08-01 09:15:44 +02:00
return Err((StatusCode::BAD_REQUEST, "No session found for cookie"));
};
Ok(Self::FoundUserId(user_id))
}
}
#[derive(Serialize, Deserialize, Debug, Clone, Copy)]
struct UserId(Uuid);
impl UserId {
fn new() -> Self {
Self(Uuid::new_v4())
}
}