use crate::{ database::{Database, User}, routes::ui::error::MyError, }; use anyhow::anyhow; use rocket::{ outcome::Outcome, request::{self, FromRequest}, Request, State, }; pub struct Session { pub user: User, } impl Session { pub async fn from_request_ut(req: &Request<'_>) -> Result { let cookie = req .cookies() .get_private("user") .ok_or(anyhow!("login required"))?; let username = cookie.value(); let db = req.guard::<&State>().await.unwrap(); let user = db .users .get(&username.to_string())? .ok_or(anyhow!("user not found"))?; Ok(Session { user }) } } impl<'r> FromRequest<'r> for Session { type Error = MyError; fn from_request<'life0, 'async_trait>( request: &'r Request<'life0>, ) -> core::pin::Pin< Box< dyn core::future::Future> + core::marker::Send + 'async_trait, >, > where 'r: 'async_trait, 'life0: 'async_trait, Self: 'async_trait, { Box::pin(async move { match Self::from_request_ut(request).await { Ok(x) => Outcome::Success(x), Err(_) => Outcome::Forward(()), } }) } }