rustbasic_core/middleware/
csrf.rs1use crate::{Request, Response, Next, IntoResponse};
2use crate::rand::distr::SampleString;
3use crate::http::{StatusCode, Method};
4
5pub async fn csrf_middleware(
6 req: Request,
7 next: Next,
8) -> Response {
9 let token = match req.session.get::<String>("_token") {
11 Some(t) => t,
12 None => {
13 let new_token = crate::rand::distr::Alphanumeric.sample_string(&mut crate::rand::rng(), 40);
14 req.session.set("_token", new_token.clone());
15 new_token
16 }
17 };
18
19 let method = &req.method;
21 if method == Method::POST || method == Method::PUT || method == Method::PATCH || method == Method::DELETE {
22 let header_token = req.headers.get("x-csrf-token").map(|s| s.as_str());
24
25 if let Some(h_token) = header_token {
26 if h_token != token {
27 return StatusCode::from_u16(419).unwrap().into_response();
28 }
29 } else {
30 return StatusCode::from_u16(419).unwrap().into_response();
31 }
32 }
33
34 next.run(req).await
35}