/* This file is part of jellything (https://codeberg.org/metamuffin/jellything) which is licensed under the GNU Affero General Public License (version 3); see /COPYING. Copyright (C) 2023 metamuffin */ use super::Session; use crate::{database::Database, routes::ui::error::MyError}; use anyhow::anyhow; use log::warn; use rocket::{ outcome::Outcome, request::{self, FromRequest}, Request, State, }; impl Session { pub async fn from_request_ut(req: &Request<'_>) -> Result { let username; #[cfg(not(feature = "bypass-auth"))] { let token = req .query_value("session") .map(|e| e.expect("str parse should not fail, right?")) .or(req.cookies().get("session").map(|cookie| cookie.value())) .ok_or(anyhow!("not logged in"))?; username = super::token::validate(token)?; }; #[cfg(feature = "bypass-auth")] { username = "admin".to_string(); } let db = req.guard::<&State>().await.unwrap(); let user = db.user.get(&username)?.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(e) => { warn!("authentificated route rejected: {e:?}"); Outcome::Forward(()) } } }) } }