Added session to be part of state.

This commit is contained in:
2024-03-19 19:54:14 -04:00
parent 0b076aac12
commit ba41b311ab
3 changed files with 143 additions and 12 deletions

View File

@ -1,7 +1,7 @@
use axum::{response::IntoResponse, routing::get, Router};
use axum::{extract::State, response::IntoResponse, routing::get, Router};
use axum_extra::extract::cookie::{Cookie, CookieJar};
use clap::Parser;
use rand::distributions::{Alphanumeric, DistString};
use morethantext::{MoreThanText, Session};
const LOCALHOST: &str = "127.0.0.1";
const SESSION_KEY: &str = "sessionid";
@ -29,26 +29,27 @@ mod http_session {
async fn main() {
let args = Args::parse();
let addr = format!("{}:{}", args.address, args.port);
let app = Router::new().route("/", get(handler));
let state = MoreThanText::new();
let app = Router::new().route("/", get(handler)).with_state(state);
let listener = tokio::net::TcpListener::bind(&addr).await.unwrap();
axum::serve(listener, app.into_make_service())
.await
.unwrap();
}
async fn handler(jar: CookieJar) -> impl IntoResponse {
async fn handler(jar: CookieJar, state: State<MoreThanText>) -> impl IntoResponse {
let cookies: CookieJar;
let id: String;
let sid: Option<String>;
match jar.get(SESSION_KEY) {
Some(session) => {
id = session.to_string();
cookies = jar;
}
None => {
id = Alphanumeric.sample_string(&mut rand::thread_rng(), 16);
Some(cookie) => sid = Some(cookie.value().to_string()),
None => sid = None,
}
match state.get_session(sid) {
Session::Ok => cookies = jar,
Session::New(id) => {
let cookie = Cookie::build((SESSION_KEY, id.clone())).domain("example.com");
cookies = jar.add(cookie);
}
}
(cookies, format!("id is {}", id))
(cookies, "Something goes here.")
}