use std::future::{Ready, ready}; use actix_web::dev::Payload; use actix_web::{FromRequest, HttpMessage, HttpRequest}; use crate::error::SessionError; use crate::state::Session; pub struct AuthedUser(pub i64); impl FromRequest for AuthedUser { type Error = actix_web::Error; type Future = Ready>; fn from_request(req: &HttpRequest, _payload: &mut Payload) -> Self::Future { let Some(session) = req.extensions().get::().cloned() else { return ready(Err(actix_web::error::ErrorInternalServerError( "session is not initialized", ))); }; match session.uid() { Some(uid) => ready(Ok(Self(uid))), None => ready(Err(SessionError::Unauthorized.into())), } } } pub struct OptionalUser(pub Option); impl FromRequest for OptionalUser { type Error = actix_web::Error; type Future = Ready>; fn from_request(req: &HttpRequest, _payload: &mut Payload) -> Self::Future { match req.extensions().get::() { Some(session) => ready(Ok(Self(session.uid()))), None => ready(Err(actix_web::error::ErrorInternalServerError( "session is not initialized", ))), } } } impl FromRequest for Session { type Error = actix_web::Error; type Future = Ready>; fn from_request(req: &HttpRequest, _payload: &mut Payload) -> Self::Future { match req.extensions().get::() { Some(session) => ready(Ok(session.clone())), None => ready(Err(actix_web::error::ErrorInternalServerError( "session is not initialized", ))), } } }