Files
MoneyMgr/moneymgr_backend/src/extractors/file_id_extractor.rs
Pierre HUBERT 2560962684
All checks were successful
continuous-integration/drone/push Build is passing
Fix cargo clippy issues
2025-07-03 08:38:56 +02:00

62 lines
1.7 KiB
Rust

use crate::extractors::auth_extractor::AuthExtractor;
use crate::models::files::{File, FileID};
use crate::services::files_service;
use actix_web::dev::Payload;
use actix_web::{FromRequest, HttpRequest};
use serde::Deserialize;
#[derive(Deserialize)]
struct FileIdInPath {
file_id: FileID,
}
#[derive(thiserror::Error, Debug)]
enum FileIdExtractorError {
#[error("Current user does not own the file!")]
UserDoesNotOwnFile,
}
pub struct FileIdExtractor(File);
impl FileIdExtractor {
pub async fn load_file_from_path(auth: &AuthExtractor, id: FileID) -> anyhow::Result<Self> {
let file = files_service::get_file_with_id(id)?;
if file.user_id() != auth.user_id() {
return Err(FileIdExtractorError::UserDoesNotOwnFile.into());
}
Ok(Self(file))
}
}
impl FromRequest for FileIdExtractor {
type Error = actix_web::Error;
type Future = futures_util::future::LocalBoxFuture<'static, Result<Self, Self::Error>>;
fn from_request(req: &HttpRequest, _payload: &mut Payload) -> Self::Future {
let req = req.clone();
Box::pin(async move {
let auth = AuthExtractor::extract(&req).await?;
let file_id =
actix_web::web::Path::<FileIdInPath>::from_request(&req, &mut Payload::None)
.await?
.file_id;
Self::load_file_from_path(&auth, file_id)
.await
.map_err(|e| {
log::error!("Failed to extract file ID from URL! {e}");
actix_web::error::ErrorNotFound("Could not fetch file information!")
})
})
}
}
impl AsRef<File> for FileIdExtractor {
fn as_ref(&self) -> &File {
&self.0
}
}