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

158 lines
4.6 KiB
Rust
Raw Normal View History

2021-08-02 23:09:09 +02:00
//! Run with
//!
//! ```not_rust
//! 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,
extract::{FromRef, FromRequestParts, TypedHeader},
2021-12-22 22:27:13 +08:00
headers::Cookie,
http::{
self,
header::{HeaderMap, HeaderValue},
request::Parts,
StatusCode,
},
2021-08-01 09:15:44 +02:00
response::IntoResponse,
routing::get,
RequestPartsExt, 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;
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::try_from_default_env()
.unwrap_or_else(|_| "example_sessions=debug".into()),
)
2022-03-06 12:37:00 +01:00
.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();
2022-11-18 12:02:58 +01:00
let app = Router::new().route("/", get(handler)).with_state(store);
2021-08-01 09:15:44 +02:00
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
2021-08-01 09:15:44 +02:00
.await
.unwrap();
tracing::debug!("listening on {}", listener.local_addr().unwrap());
axum::serve(listener, app).await.unwrap();
2021-08-01 09:15:44 +02:00
}
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<S> FromRequestParts<S> for UserIdFromSession
2021-08-01 09:15:44 +02:00
where
MemoryStore: FromRef<S>,
S: Send + Sync,
2021-08-01 09:15:44 +02:00
{
type Rejection = (StatusCode, &'static str);
async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
let store = MemoryStore::from_ref(state);
2021-08-01 09:15:44 +02:00
let cookie: Option<TypedHeader<Cookie>> = parts.extract().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())
}
}