Refactor how ResourceService works

This commit is contained in:
Lennart
2025-01-04 14:24:01 +01:00
parent 40c8624703
commit c19e4745f9
16 changed files with 203 additions and 250 deletions

View File

@@ -1,3 +1,2 @@
pub mod mkcalendar; pub mod mkcalendar;
pub mod post;
pub mod report; pub mod report;

View File

@@ -1,15 +0,0 @@
use actix_web::{web::Data, web::Path, Responder};
use rustical_store::{auth::User, CalendarStore};
use tracing::instrument;
use tracing_actix_web::RootSpan;
#[instrument(parent = root_span.id(), skip(store, root_span))]
pub async fn route_post<C: CalendarStore + ?Sized>(
path: Path<(String, String)>,
body: String,
user: User,
store: Data<C>,
root_span: RootSpan,
) -> impl Responder {
"asd"
}

View File

@@ -1,9 +1,7 @@
use super::methods::mkcalendar::route_mkcalendar; use super::methods::mkcalendar::route_mkcalendar;
use super::methods::post::route_post;
use super::methods::report::route_report_calendar; use super::methods::report::route_report_calendar;
use super::prop::{ use super::prop::{
SupportedCalendarComponent, SupportedCalendarComponentSet, SupportedCalendarData, SupportedCalendarComponentSet, SupportedCalendarData, SupportedReportSet, Transports,
SupportedReportSet, Transports,
}; };
use crate::calendar_object::resource::CalendarObjectResource; use crate::calendar_object::resource::CalendarObjectResource;
use crate::principal::PrincipalResource; use crate::principal::PrincipalResource;
@@ -11,7 +9,6 @@ use crate::Error;
use actix_web::dev::ResourceMap; use actix_web::dev::ResourceMap;
use actix_web::http::Method; use actix_web::http::Method;
use actix_web::web; use actix_web::web;
use actix_web::{web::Data, HttpRequest};
use async_trait::async_trait; use async_trait::async_trait;
use derive_more::derive::{From, Into}; use derive_more::derive::{From, Into};
use rustical_dav::privileges::UserPrivilegeSet; use rustical_dav::privileges::UserPrivilegeSet;
@@ -27,8 +24,12 @@ use strum::{EnumDiscriminants, EnumString, IntoStaticStr, VariantNames};
pub struct CalendarResourceService<C: CalendarStore + ?Sized> { pub struct CalendarResourceService<C: CalendarStore + ?Sized> {
cal_store: Arc<C>, cal_store: Arc<C>,
principal: String, }
calendar_id: String,
impl<C: CalendarStore + ?Sized> CalendarResourceService<C> {
pub fn new(cal_store: Arc<C>) -> Self {
Self { cal_store }
}
} }
#[derive(XmlDeserialize, XmlSerialize, PartialEq, EnumDiscriminants, Clone)] #[derive(XmlDeserialize, XmlSerialize, PartialEq, EnumDiscriminants, Clone)]
@@ -243,10 +244,13 @@ impl<C: CalendarStore + ?Sized> ResourceService for CalendarResourceService<C> {
type Resource = CalendarResource; type Resource = CalendarResource;
type Error = Error; type Error = Error;
async fn get_resource(&self) -> Result<Self::Resource, Error> { async fn get_resource(
&self,
(principal, cal_id): &Self::PathComponents,
) -> Result<Self::Resource, Error> {
let calendar = self let calendar = self
.cal_store .cal_store
.get_calendar(&self.principal, &self.calendar_id) .get_calendar(principal, cal_id)
.await .await
.map_err(|_e| Error::NotFound)?; .map_err(|_e| Error::NotFound)?;
Ok(calendar.into()) Ok(calendar.into())
@@ -254,60 +258,45 @@ impl<C: CalendarStore + ?Sized> ResourceService for CalendarResourceService<C> {
async fn get_members( async fn get_members(
&self, &self,
(principal, cal_id): &Self::PathComponents,
rmap: &ResourceMap, rmap: &ResourceMap,
) -> Result<Vec<(String, Self::MemberType)>, Self::Error> { ) -> Result<Vec<(String, Self::MemberType)>, Self::Error> {
Ok(self Ok(self
.cal_store .cal_store
.get_objects(&self.principal, &self.calendar_id) .get_objects(principal, cal_id)
.await? .await?
.into_iter() .into_iter()
.map(|object| { .map(|object| {
( (
CalendarObjectResource::get_url( CalendarObjectResource::get_url(rmap, vec![principal, cal_id, object.get_id()])
rmap, .unwrap(),
vec![&self.principal, &self.calendar_id, object.get_id()],
)
.unwrap(),
CalendarObjectResource { CalendarObjectResource {
object, object,
principal: self.principal.to_owned(), principal: principal.to_owned(),
}, },
) )
}) })
.collect()) .collect())
} }
async fn new( async fn save_resource(
req: &HttpRequest, &self,
path_components: Self::PathComponents, (principal, cal_id): &Self::PathComponents,
) -> Result<Self, Self::Error> { file: Self::Resource,
let cal_store = req ) -> Result<(), Self::Error> {
.app_data::<Data<C>>()
.expect("no calendar store in app_data!")
.clone()
.into_inner();
Ok(Self {
principal: path_components.0,
calendar_id: path_components.1,
cal_store,
})
}
async fn save_resource(&self, file: Self::Resource) -> Result<(), Self::Error> {
self.cal_store self.cal_store
.update_calendar( .update_calendar(principal.to_owned(), cal_id.to_owned(), file.into())
self.principal.to_owned(),
self.calendar_id.to_owned(),
file.into(),
)
.await?; .await?;
Ok(()) Ok(())
} }
async fn delete_resource(&self, use_trashbin: bool) -> Result<(), Self::Error> { async fn delete_resource(
&self,
(principal, cal_id): &Self::PathComponents,
use_trashbin: bool,
) -> Result<(), Self::Error> {
self.cal_store self.cal_store
.delete_calendar(&self.principal, &self.calendar_id, use_trashbin) .delete_calendar(principal, cal_id, use_trashbin)
.await?; .await?;
Ok(()) Ok(())
} }
@@ -319,6 +308,5 @@ impl<C: CalendarStore + ?Sized> ResourceService for CalendarResourceService<C> {
res.route(report_method.to(route_report_calendar::<C>)) res.route(report_method.to(route_report_calendar::<C>))
.route(mkcalendar_method.to(route_mkcalendar::<C>)) .route(mkcalendar_method.to(route_mkcalendar::<C>))
.post(route_post::<C>)
} }
} }

View File

@@ -1,6 +1,6 @@
use super::methods::{get_event, put_event}; use super::methods::{get_event, put_event};
use crate::{principal::PrincipalResource, Error}; use crate::{principal::PrincipalResource, Error};
use actix_web::{dev::ResourceMap, web::Data, HttpRequest}; use actix_web::dev::ResourceMap;
use async_trait::async_trait; use async_trait::async_trait;
use derive_more::derive::{From, Into}; use derive_more::derive::{From, Into};
use rustical_dav::{ use rustical_dav::{
@@ -15,9 +15,12 @@ use strum::{EnumDiscriminants, EnumString, IntoStaticStr, VariantNames};
pub struct CalendarObjectResourceService<C: CalendarStore + ?Sized> { pub struct CalendarObjectResourceService<C: CalendarStore + ?Sized> {
cal_store: Arc<C>, cal_store: Arc<C>,
principal: String, }
cal_id: String,
object_id: String, impl<C: CalendarStore + ?Sized> CalendarObjectResourceService<C> {
pub fn new(cal_store: Arc<C>) -> Self {
Self { cal_store }
}
} }
#[derive(XmlDeserialize, XmlSerialize, PartialEq, EnumDiscriminants, Clone)] #[derive(XmlDeserialize, XmlSerialize, PartialEq, EnumDiscriminants, Clone)]
@@ -117,44 +120,35 @@ impl<C: CalendarStore + ?Sized> ResourceService for CalendarObjectResourceServic
type MemberType = CalendarObjectResource; type MemberType = CalendarObjectResource;
type Error = Error; type Error = Error;
async fn new( async fn get_resource(
req: &HttpRequest, &self,
path_components: Self::PathComponents, CalendarObjectPathComponents {
) -> Result<Self, Self::Error> {
let CalendarObjectPathComponents {
principal, principal,
cal_id, cal_id,
object_id, object_id,
} = path_components; }: &Self::PathComponents,
) -> Result<Self::Resource, Self::Error> {
let cal_store = req
.app_data::<Data<C>>()
.expect("no calendar store in app_data!")
.clone()
.into_inner();
Ok(Self {
cal_store,
principal,
cal_id,
object_id,
})
}
async fn get_resource(&self) -> Result<Self::Resource, Self::Error> {
let object = self let object = self
.cal_store .cal_store
.get_object(&self.principal, &self.cal_id, &self.object_id) .get_object(principal, cal_id, object_id)
.await?; .await?;
Ok(CalendarObjectResource { Ok(CalendarObjectResource {
object, object,
principal: self.principal.to_owned(), principal: principal.to_owned(),
}) })
} }
async fn delete_resource(&self, use_trashbin: bool) -> Result<(), Self::Error> { async fn delete_resource(
&self,
CalendarObjectPathComponents {
principal,
cal_id,
object_id,
}: &Self::PathComponents,
use_trashbin: bool,
) -> Result<(), Self::Error> {
self.cal_store self.cal_store
.delete_object(&self.principal, &self.cal_id, &self.object_id, use_trashbin) .delete_object(principal, cal_id, object_id, use_trashbin)
.await?; .await?;
Ok(()) Ok(())
} }

View File

@@ -52,17 +52,21 @@ pub fn configure_dav<AP: AuthenticationProvider, C: CalendarStore + ?Sized>(
}), }),
) )
.app_data(Data::from(store.clone())) .app_data(Data::from(store.clone()))
.service(RootResourceService::<PrincipalResource>::actix_resource()) .service(RootResourceService::<PrincipalResource>::default().actix_resource())
.service( .service(
web::scope("/user").service( web::scope("/user").service(
web::scope("/{principal}") web::scope("/{principal}")
.service(PrincipalResourceService::<C>::actix_resource()) .service(PrincipalResourceService::<C>::new(store.clone()).actix_resource())
.service( .service(
web::scope("/{calendar}") web::scope("/{calendar}")
.service(CalendarResourceService::<C>::actix_resource()) .service(
CalendarResourceService::<C>::new(store.clone())
.actix_resource(),
)
.service( .service(
web::scope("/{object}").service( web::scope("/{object}").service(
CalendarObjectResourceService::<C>::actix_resource(), CalendarObjectResourceService::<C>::new(store.clone())
.actix_resource(),
), ),
), ),
), ),

View File

@@ -1,8 +1,6 @@
use crate::calendar::resource::CalendarResource; use crate::calendar::resource::CalendarResource;
use crate::Error; use crate::Error;
use actix_web::dev::ResourceMap; use actix_web::dev::ResourceMap;
use actix_web::web::Data;
use actix_web::HttpRequest;
use async_trait::async_trait; use async_trait::async_trait;
use rustical_dav::privileges::UserPrivilegeSet; use rustical_dav::privileges::UserPrivilegeSet;
use rustical_dav::resource::{Resource, ResourceService}; use rustical_dav::resource::{Resource, ResourceService};
@@ -14,10 +12,15 @@ use std::sync::Arc;
use strum::{EnumDiscriminants, EnumString, IntoStaticStr, VariantNames}; use strum::{EnumDiscriminants, EnumString, IntoStaticStr, VariantNames};
pub struct PrincipalResourceService<C: CalendarStore + ?Sized> { pub struct PrincipalResourceService<C: CalendarStore + ?Sized> {
principal: String,
cal_store: Arc<C>, cal_store: Arc<C>,
} }
impl<C: CalendarStore + ?Sized> PrincipalResourceService<C> {
pub fn new(cal_store: Arc<C>) -> Self {
Self { cal_store }
}
}
#[derive(Clone)] #[derive(Clone)]
pub struct PrincipalResource { pub struct PrincipalResource {
principal: String, principal: String,
@@ -96,38 +99,26 @@ impl<C: CalendarStore + ?Sized> ResourceService for PrincipalResourceService<C>
type Resource = PrincipalResource; type Resource = PrincipalResource;
type Error = Error; type Error = Error;
async fn new( async fn get_resource(
req: &HttpRequest, &self,
(principal,): Self::PathComponents, (principal,): &Self::PathComponents,
) -> Result<Self, Self::Error> { ) -> Result<Self::Resource, Self::Error> {
let cal_store = req
.app_data::<Data<C>>()
.expect("no calendar store in app_data!")
.clone()
.into_inner();
Ok(Self {
cal_store,
principal,
})
}
async fn get_resource(&self) -> Result<Self::Resource, Self::Error> {
Ok(PrincipalResource { Ok(PrincipalResource {
principal: self.principal.to_owned(), principal: principal.to_owned(),
}) })
} }
async fn get_members( async fn get_members(
&self, &self,
(principal,): &Self::PathComponents,
rmap: &ResourceMap, rmap: &ResourceMap,
) -> Result<Vec<(String, Self::MemberType)>, Self::Error> { ) -> Result<Vec<(String, Self::MemberType)>, Self::Error> {
let calendars = self.cal_store.get_calendars(&self.principal).await?; let calendars = self.cal_store.get_calendars(principal).await?;
Ok(calendars Ok(calendars
.into_iter() .into_iter()
.map(|cal| { .map(|cal| {
( (
CalendarResource::get_url(rmap, vec![&self.principal, &cal.id]).unwrap(), CalendarResource::get_url(rmap, vec![principal, &cal.id]).unwrap(),
cal.into(), cal.into(),
) )
}) })

View File

@@ -19,7 +19,7 @@ pub async fn get_object<AS: AddressbookStore + ?Sized>(
) -> Result<HttpResponse, Error> { ) -> Result<HttpResponse, Error> {
let AddressObjectPathComponents { let AddressObjectPathComponents {
principal, principal,
cal_id, addressbook_id,
object_id, object_id,
} = path.into_inner(); } = path.into_inner();
@@ -27,12 +27,14 @@ pub async fn get_object<AS: AddressbookStore + ?Sized>(
return Ok(HttpResponse::Unauthorized().body("")); return Ok(HttpResponse::Unauthorized().body(""));
} }
let addressbook = store.get_addressbook(&principal, &cal_id).await?; let addressbook = store.get_addressbook(&principal, &addressbook_id).await?;
if user.id != addressbook.principal { if user.id != addressbook.principal {
return Ok(HttpResponse::Unauthorized().body("")); return Ok(HttpResponse::Unauthorized().body(""));
} }
let object = store.get_object(&principal, &cal_id, &object_id).await?; let object = store
.get_object(&principal, &addressbook_id, &object_id)
.await?;
Ok(HttpResponse::Ok() Ok(HttpResponse::Ok()
.insert_header(("ETag", object.get_etag())) .insert_header(("ETag", object.get_etag()))
@@ -51,7 +53,7 @@ pub async fn put_object<AS: AddressbookStore + ?Sized>(
) -> Result<HttpResponse, Error> { ) -> Result<HttpResponse, Error> {
let AddressObjectPathComponents { let AddressObjectPathComponents {
principal, principal,
cal_id: addressbook_id, addressbook_id,
object_id, object_id,
} = path.into_inner(); } = path.into_inner();

View File

@@ -1,5 +1,5 @@
use crate::{principal::PrincipalResource, Error}; use crate::{principal::PrincipalResource, Error};
use actix_web::{dev::ResourceMap, web::Data, HttpRequest}; use actix_web::dev::ResourceMap;
use async_trait::async_trait; use async_trait::async_trait;
use derive_more::derive::{From, Into}; use derive_more::derive::{From, Into};
use rustical_dav::{ use rustical_dav::{
@@ -16,9 +16,12 @@ use super::methods::{get_object, put_object};
pub struct AddressObjectResourceService<AS: AddressbookStore + ?Sized> { pub struct AddressObjectResourceService<AS: AddressbookStore + ?Sized> {
addr_store: Arc<AS>, addr_store: Arc<AS>,
principal: String, }
cal_id: String,
object_id: String, impl<A: AddressbookStore + ?Sized> AddressObjectResourceService<A> {
pub fn new(addr_store: Arc<A>) -> Self {
Self { addr_store }
}
} }
#[derive(XmlDeserialize, XmlSerialize, PartialEq, EnumDiscriminants, Clone)] #[derive(XmlDeserialize, XmlSerialize, PartialEq, EnumDiscriminants, Clone)]
@@ -89,7 +92,7 @@ impl Resource for AddressObjectResource {
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct AddressObjectPathComponents { pub struct AddressObjectPathComponents {
pub principal: String, pub principal: String,
pub cal_id: String, pub addressbook_id: String,
pub object_id: String, pub object_id: String,
} }
@@ -99,13 +102,13 @@ impl<'de> Deserialize<'de> for AddressObjectPathComponents {
D: serde::Deserializer<'de>, D: serde::Deserializer<'de>,
{ {
type Inner = (String, String, String); type Inner = (String, String, String);
let (principal, calendar, mut object) = Inner::deserialize(deserializer)?; let (principal, addressbook_id, mut object) = Inner::deserialize(deserializer)?;
if object.ends_with(".vcf") { if object.ends_with(".vcf") {
object.truncate(object.len() - 4); object.truncate(object.len() - 4);
} }
Ok(Self { Ok(Self {
principal, principal,
cal_id: calendar, addressbook_id,
object_id: object, object_id: object,
}) })
} }
@@ -118,44 +121,35 @@ impl<AS: AddressbookStore + ?Sized> ResourceService for AddressObjectResourceSer
type MemberType = AddressObjectResource; type MemberType = AddressObjectResource;
type Error = Error; type Error = Error;
async fn new( async fn get_resource(
req: &HttpRequest, &self,
path_components: Self::PathComponents, AddressObjectPathComponents {
) -> Result<Self, Self::Error> {
let AddressObjectPathComponents {
principal, principal,
cal_id, addressbook_id,
object_id, object_id,
} = path_components; }: &Self::PathComponents,
) -> Result<Self::Resource, Self::Error> {
let addr_store = req
.app_data::<Data<AS>>()
.expect("no addressbook store in app_data!")
.clone()
.into_inner();
Ok(Self {
addr_store,
principal,
cal_id,
object_id,
})
}
async fn get_resource(&self) -> Result<Self::Resource, Self::Error> {
let object = self let object = self
.addr_store .addr_store
.get_object(&self.principal, &self.cal_id, &self.object_id) .get_object(principal, addressbook_id, object_id)
.await?; .await?;
Ok(AddressObjectResource { Ok(AddressObjectResource {
object, object,
principal: self.principal.to_owned(), principal: principal.to_owned(),
}) })
} }
async fn delete_resource(&self, use_trashbin: bool) -> Result<(), Self::Error> { async fn delete_resource(
&self,
AddressObjectPathComponents {
principal,
addressbook_id,
object_id,
}: &Self::PathComponents,
use_trashbin: bool,
) -> Result<(), Self::Error> {
self.addr_store self.addr_store
.delete_object(&self.principal, &self.cal_id, &self.object_id, use_trashbin) .delete_object(principal, addressbook_id, object_id, use_trashbin)
.await?; .await?;
Ok(()) Ok(())
} }

View File

@@ -7,7 +7,6 @@ use crate::Error;
use actix_web::dev::ResourceMap; use actix_web::dev::ResourceMap;
use actix_web::http::Method; use actix_web::http::Method;
use actix_web::web; use actix_web::web;
use actix_web::{web::Data, HttpRequest};
use async_trait::async_trait; use async_trait::async_trait;
use derive_more::derive::{From, Into}; use derive_more::derive::{From, Into};
use rustical_dav::privileges::UserPrivilegeSet; use rustical_dav::privileges::UserPrivilegeSet;
@@ -21,8 +20,12 @@ use strum::{EnumDiscriminants, EnumString, IntoStaticStr, VariantNames};
pub struct AddressbookResourceService<AS: AddressbookStore + ?Sized> { pub struct AddressbookResourceService<AS: AddressbookStore + ?Sized> {
addr_store: Arc<AS>, addr_store: Arc<AS>,
principal: String, }
addressbook_id: String,
impl<A: AddressbookStore + ?Sized> AddressbookResourceService<A> {
pub fn new(addr_store: Arc<A>) -> Self {
Self { addr_store }
}
} }
#[derive(XmlDeserialize, XmlSerialize, PartialEq, EnumDiscriminants, Clone)] #[derive(XmlDeserialize, XmlSerialize, PartialEq, EnumDiscriminants, Clone)]
@@ -157,10 +160,13 @@ impl<AS: AddressbookStore + ?Sized> ResourceService for AddressbookResourceServi
type Resource = AddressbookResource; type Resource = AddressbookResource;
type Error = Error; type Error = Error;
async fn get_resource(&self) -> Result<Self::Resource, Error> { async fn get_resource(
&self,
(principal, addressbook_id): &Self::PathComponents,
) -> Result<Self::Resource, Error> {
let addressbook = self let addressbook = self
.addr_store .addr_store
.get_addressbook(&self.principal, &self.addressbook_id) .get_addressbook(principal, addressbook_id)
.await .await
.map_err(|_e| Error::NotFound)?; .map_err(|_e| Error::NotFound)?;
Ok(addressbook.into()) Ok(addressbook.into())
@@ -168,60 +174,48 @@ impl<AS: AddressbookStore + ?Sized> ResourceService for AddressbookResourceServi
async fn get_members( async fn get_members(
&self, &self,
(principal, addressbook_id): &Self::PathComponents,
rmap: &ResourceMap, rmap: &ResourceMap,
) -> Result<Vec<(String, Self::MemberType)>, Self::Error> { ) -> Result<Vec<(String, Self::MemberType)>, Self::Error> {
Ok(self Ok(self
.addr_store .addr_store
.get_objects(&self.principal, &self.addressbook_id) .get_objects(principal, addressbook_id)
.await? .await?
.into_iter() .into_iter()
.map(|object| { .map(|object| {
( (
AddressObjectResource::get_url( AddressObjectResource::get_url(
rmap, rmap,
vec![&self.principal, &self.addressbook_id, object.get_id()], vec![principal, addressbook_id, object.get_id()],
) )
.unwrap(), .unwrap(),
AddressObjectResource { AddressObjectResource {
object, object,
principal: self.principal.to_owned(), principal: principal.to_owned(),
}, },
) )
}) })
.collect()) .collect())
} }
async fn new( async fn save_resource(
req: &HttpRequest, &self,
path_components: Self::PathComponents, (principal, addressbook_id): &Self::PathComponents,
) -> Result<Self, Self::Error> { file: Self::Resource,
let addr_store = req ) -> Result<(), Self::Error> {
.app_data::<Data<AS>>()
.expect("no addressbook store in app_data!")
.clone()
.into_inner();
Ok(Self {
principal: path_components.0,
addressbook_id: path_components.1,
addr_store,
})
}
async fn save_resource(&self, file: Self::Resource) -> Result<(), Self::Error> {
self.addr_store self.addr_store
.update_addressbook( .update_addressbook(principal.to_owned(), addressbook_id.to_owned(), file.into())
self.principal.to_owned(),
self.addressbook_id.to_owned(),
file.into(),
)
.await?; .await?;
Ok(()) Ok(())
} }
async fn delete_resource(&self, use_trashbin: bool) -> Result<(), Self::Error> { async fn delete_resource(
&self,
(principal, addressbook_id): &Self::PathComponents,
use_trashbin: bool,
) -> Result<(), Self::Error> {
self.addr_store self.addr_store
.delete_addressbook(&self.principal, &self.addressbook_id, use_trashbin) .delete_addressbook(principal, addressbook_id, use_trashbin)
.await?; .await?;
Ok(()) Ok(())
} }

View File

@@ -57,17 +57,21 @@ pub fn configure_dav<AP: AuthenticationProvider, A: AddressbookStore + ?Sized>(
}), }),
) )
.app_data(Data::from(store.clone())) .app_data(Data::from(store.clone()))
.service(RootResourceService::<PrincipalResource>::actix_resource()) .service(RootResourceService::<PrincipalResource>::default().actix_resource())
.service( .service(
web::scope("/user").service( web::scope("/user").service(
web::scope("/{principal}") web::scope("/{principal}")
.service(PrincipalResourceService::<A>::actix_resource()) .service(PrincipalResourceService::<A>::new(store.clone()).actix_resource())
.service( .service(
web::scope("/{addressbook}") web::scope("/{addressbook}")
.service(AddressbookResourceService::<A>::actix_resource()) .service(
AddressbookResourceService::<A>::new(store.clone())
.actix_resource(),
)
.service( .service(
web::scope("/{object}").service( web::scope("/{object}").service(
AddressObjectResourceService::<A>::actix_resource(), AddressObjectResourceService::<A>::new(store.clone())
.actix_resource(),
), ),
), ),
), ),

View File

@@ -1,8 +1,6 @@
use crate::addressbook::resource::AddressbookResource; use crate::addressbook::resource::AddressbookResource;
use crate::Error; use crate::Error;
use actix_web::dev::ResourceMap; use actix_web::dev::ResourceMap;
use actix_web::web::Data;
use actix_web::HttpRequest;
use async_trait::async_trait; use async_trait::async_trait;
use rustical_dav::privileges::UserPrivilegeSet; use rustical_dav::privileges::UserPrivilegeSet;
use rustical_dav::resource::{Resource, ResourceService}; use rustical_dav::resource::{Resource, ResourceService};
@@ -14,10 +12,15 @@ use std::sync::Arc;
use strum::{EnumDiscriminants, EnumString, IntoStaticStr, VariantNames}; use strum::{EnumDiscriminants, EnumString, IntoStaticStr, VariantNames};
pub struct PrincipalResourceService<A: AddressbookStore + ?Sized> { pub struct PrincipalResourceService<A: AddressbookStore + ?Sized> {
principal: String,
addr_store: Arc<A>, addr_store: Arc<A>,
} }
impl<A: AddressbookStore + ?Sized> PrincipalResourceService<A> {
pub fn new(addr_store: Arc<A>) -> Self {
Self { addr_store }
}
}
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct PrincipalResource { pub struct PrincipalResource {
principal: String, principal: String,
@@ -97,39 +100,26 @@ impl<A: AddressbookStore + ?Sized> ResourceService for PrincipalResourceService<
type Resource = PrincipalResource; type Resource = PrincipalResource;
type Error = Error; type Error = Error;
async fn new( async fn get_resource(
req: &HttpRequest, &self,
(principal,): Self::PathComponents, (principal,): &Self::PathComponents,
) -> Result<Self, Self::Error> { ) -> Result<Self::Resource, Self::Error> {
let addr_store = req
.app_data::<Data<A>>()
.expect("no addressbook store in app_data!")
.clone()
.into_inner();
Ok(Self {
addr_store,
principal,
})
}
async fn get_resource(&self) -> Result<Self::Resource, Self::Error> {
Ok(PrincipalResource { Ok(PrincipalResource {
principal: self.principal.to_owned(), principal: principal.to_owned(),
}) })
} }
async fn get_members( async fn get_members(
&self, &self,
(principal,): &Self::PathComponents,
rmap: &ResourceMap, rmap: &ResourceMap,
) -> Result<Vec<(String, Self::MemberType)>, Self::Error> { ) -> Result<Vec<(String, Self::MemberType)>, Self::Error> {
let addressbooks = self.addr_store.get_addressbooks(&self.principal).await?; let addressbooks = self.addr_store.get_addressbooks(principal).await?;
Ok(addressbooks Ok(addressbooks
.into_iter() .into_iter()
.map(|addressbook| { .map(|addressbook| {
( (
AddressbookResource::get_url(rmap, vec![&self.principal, &addressbook.id]) AddressbookResource::get_url(rmap, vec![principal, &addressbook.id]).unwrap(),
.unwrap(),
addressbook.into(), addressbook.into(),
) )
}) })

View File

@@ -2,6 +2,7 @@ use crate::privileges::UserPrivilege;
use crate::resource::Resource; use crate::resource::Resource;
use crate::resource::ResourceService; use crate::resource::ResourceService;
use crate::Error; use crate::Error;
use actix_web::web::Data;
use actix_web::web::Path; use actix_web::web::Path;
use actix_web::HttpRequest; use actix_web::HttpRequest;
use actix_web::HttpResponse; use actix_web::HttpResponse;
@@ -9,27 +10,25 @@ use actix_web::Responder;
use rustical_store::auth::User; use rustical_store::auth::User;
pub async fn route_delete<R: ResourceService>( pub async fn route_delete<R: ResourceService>(
path_components: Path<R::PathComponents>, path: Path<R::PathComponents>,
req: HttpRequest, req: HttpRequest,
user: User, user: User,
resource_service: Data<R>,
) -> Result<impl Responder, R::Error> { ) -> Result<impl Responder, R::Error> {
let path_components = path_components.into_inner();
let no_trash = req let no_trash = req
.headers() .headers()
.get("X-No-Trashbin") .get("X-No-Trashbin")
.map(|val| matches!(val.to_str(), Ok("1"))) .map(|val| matches!(val.to_str(), Ok("1")))
.unwrap_or(false); .unwrap_or(false);
let resource_service = R::new(&req, path_components.clone()).await?; let resource = resource_service.get_resource(&path).await?;
let resource = resource_service.get_resource().await?;
let privileges = resource.get_user_privileges(&user)?; let privileges = resource.get_user_privileges(&user)?;
if !privileges.has(&UserPrivilege::Write) { if !privileges.has(&UserPrivilege::Write) {
// TODO: Actually the spec wants us to look whether we have unbind access in the parent // TODO: Actually the spec wants us to look whether we have unbind access in the parent
// collection // collection
return Err(Error::Unauthorized.into()); return Err(Error::Unauthorized.into());
} }
resource_service.delete_resource(!no_trash).await?; resource_service.delete_resource(&path, !no_trash).await?;
Ok(HttpResponse::Ok().body("")) Ok(HttpResponse::Ok().body(""))
} }

View File

@@ -9,6 +9,7 @@ use crate::xml::PropElement;
use crate::xml::PropfindElement; use crate::xml::PropfindElement;
use crate::xml::PropfindType; use crate::xml::PropfindType;
use crate::Error; use crate::Error;
use actix_web::web::Data;
use actix_web::web::Path; use actix_web::web::Path;
use actix_web::HttpRequest; use actix_web::HttpRequest;
use rustical_store::auth::User; use rustical_store::auth::User;
@@ -16,15 +17,16 @@ use rustical_xml::de::XmlDocument;
use tracing::instrument; use tracing::instrument;
use tracing_actix_web::RootSpan; use tracing_actix_web::RootSpan;
#[instrument(parent = root_span.id(), skip(path_components, req, root_span))] #[instrument(parent = root_span.id(), skip(path, req, root_span, resource_service))]
#[allow(clippy::type_complexity)] #[allow(clippy::type_complexity)]
pub(crate) async fn route_propfind<R: ResourceService>( pub(crate) async fn route_propfind<R: ResourceService>(
path_components: Path<R::PathComponents>, path: Path<R::PathComponents>,
body: String, body: String,
req: HttpRequest, req: HttpRequest,
user: User, user: User,
depth: Depth, depth: Depth,
root_span: RootSpan, root_span: RootSpan,
resource_service: Data<R>,
) -> Result< ) -> Result<
MultistatusElement< MultistatusElement<
EitherProp<<R::Resource as Resource>::Prop, CommonPropertiesProp>, EitherProp<<R::Resource as Resource>::Prop, CommonPropertiesProp>,
@@ -32,9 +34,7 @@ pub(crate) async fn route_propfind<R: ResourceService>(
>, >,
R::Error, R::Error,
> { > {
let resource_service = R::new(&req, path_components.into_inner()).await?; let resource = resource_service.get_resource(&path).await?;
let resource = resource_service.get_resource().await?;
let privileges = resource.get_user_privileges(&user)?; let privileges = resource.get_user_privileges(&user)?;
if !privileges.has(&UserPrivilege::Read) { if !privileges.has(&UserPrivilege::Read) {
return Err(Error::Unauthorized.into()); return Err(Error::Unauthorized.into());
@@ -61,7 +61,10 @@ pub(crate) async fn route_propfind<R: ResourceService>(
let mut member_responses = Vec::new(); let mut member_responses = Vec::new();
if depth != Depth::Zero { if depth != Depth::Zero {
for (path, member) in resource_service.get_members(req.resource_map()).await? { for (path, member) in resource_service
.get_members(&path, req.resource_map())
.await?
{
member_responses.push(member.propfind(&path, &props, &user, req.resource_map())?); member_responses.push(member.propfind(&path, &props, &user, req.resource_map())?);
} }
} }

View File

@@ -6,6 +6,7 @@ use crate::xml::MultistatusElement;
use crate::xml::TagList; use crate::xml::TagList;
use crate::Error; use crate::Error;
use actix_web::http::StatusCode; use actix_web::http::StatusCode;
use actix_web::web::Data;
use actix_web::{web::Path, HttpRequest}; use actix_web::{web::Path, HttpRequest};
use rustical_store::auth::User; use rustical_store::auth::User;
use rustical_xml::Unparsed; use rustical_xml::Unparsed;
@@ -71,24 +72,23 @@ struct PropertyupdateElement<T: XmlDeserialize> {
operations: Vec<Operation<T>>, operations: Vec<Operation<T>>,
} }
#[instrument(parent = root_span.id(), skip(path, req, root_span))] #[instrument(parent = root_span.id(), skip(path, req, root_span, resource_service))]
pub(crate) async fn route_proppatch<R: ResourceService>( pub(crate) async fn route_proppatch<R: ResourceService>(
path: Path<R::PathComponents>, path: Path<R::PathComponents>,
body: String, body: String,
req: HttpRequest, req: HttpRequest,
user: User, user: User,
root_span: RootSpan, root_span: RootSpan,
resource_service: Data<R>,
) -> Result<MultistatusElement<String, String>, R::Error> { ) -> Result<MultistatusElement<String, String>, R::Error> {
let path_components = path.into_inner();
let href = req.path().to_owned(); let href = req.path().to_owned();
let resource_service = R::new(&req, path_components.clone()).await?;
// Extract operations // Extract operations
let PropertyupdateElement::<SetPropertyPropWrapperWrapper<<R::Resource as Resource>::Prop>> { let PropertyupdateElement::<SetPropertyPropWrapperWrapper<<R::Resource as Resource>::Prop>> {
operations, operations,
} = XmlDocument::parse_str(&body).map_err(Error::XmlDeserializationError)?; } = XmlDocument::parse_str(&body).map_err(Error::XmlDeserializationError)?;
let mut resource = resource_service.get_resource().await?; let mut resource = resource_service.get_resource(&path).await?;
let privileges = resource.get_user_privileges(&user)?; let privileges = resource.get_user_privileges(&user)?;
if !privileges.has(&UserPrivilege::Write) { if !privileges.has(&UserPrivilege::Write) {
return Err(Error::Unauthorized.into()); return Err(Error::Unauthorized.into());
@@ -141,7 +141,7 @@ pub(crate) async fn route_proppatch<R: ResourceService>(
if props_not_found.is_empty() && props_conflict.is_empty() { if props_not_found.is_empty() && props_conflict.is_empty() {
// Only save if no errors occured // Only save if no errors occured
resource_service.save_resource(resource).await?; resource_service.save_resource(&path, resource).await?;
} }
Ok(MultistatusElement { Ok(MultistatusElement {

View File

@@ -1,6 +1,7 @@
use std::str::FromStr; use std::str::FromStr;
use actix_web::{dev::ResourceMap, http::Method, web, HttpRequest, ResponseError}; use actix_web::web::Data;
use actix_web::{dev::ResourceMap, http::Method, web, ResponseError};
use async_trait::async_trait; use async_trait::async_trait;
use serde::Deserialize; use serde::Deserialize;
@@ -14,23 +15,30 @@ pub trait ResourceService: Sized + 'static {
type Resource: Resource<Error = Self::Error>; type Resource: Resource<Error = Self::Error>;
type Error: ResponseError + From<crate::Error>; type Error: ResponseError + From<crate::Error>;
async fn new(
req: &HttpRequest,
path_components: Self::PathComponents,
) -> Result<Self, Self::Error>;
async fn get_members( async fn get_members(
&self, &self,
path: &Self::PathComponents,
_rmap: &ResourceMap, _rmap: &ResourceMap,
) -> Result<Vec<(String, Self::MemberType)>, Self::Error> { ) -> Result<Vec<(String, Self::MemberType)>, Self::Error> {
Ok(vec![]) Ok(vec![])
} }
async fn get_resource(&self) -> Result<Self::Resource, Self::Error>; async fn get_resource(
async fn save_resource(&self, _file: Self::Resource) -> Result<(), Self::Error> { &self,
path: &Self::PathComponents,
) -> Result<Self::Resource, Self::Error>;
async fn save_resource(
&self,
path: &Self::PathComponents,
file: Self::Resource,
) -> Result<(), Self::Error> {
Err(crate::Error::Unauthorized.into()) Err(crate::Error::Unauthorized.into())
} }
async fn delete_resource(&self, _use_trashbin: bool) -> Result<(), Self::Error> { async fn delete_resource(
&self,
path: &Self::PathComponents,
_use_trashbin: bool,
) -> Result<(), Self::Error> {
Err(crate::Error::Unauthorized.into()) Err(crate::Error::Unauthorized.into())
} }
@@ -40,9 +48,10 @@ pub trait ResourceService: Sized + 'static {
} }
#[inline] #[inline]
fn actix_resource() -> actix_web::Resource { fn actix_resource(self) -> actix_web::Resource {
Self::actix_additional_routes( Self::actix_additional_routes(
web::resource("") web::resource("")
.app_data(Data::new(self))
.name(Self::resource_name()) .name(Self::resource_name())
.route( .route(
web::method(Method::from_str("PROPFIND").unwrap()).to(route_propfind::<Self>), web::method(Method::from_str("PROPFIND").unwrap()).to(route_propfind::<Self>),

View File

@@ -1,7 +1,6 @@
use crate::privileges::UserPrivilegeSet; use crate::privileges::UserPrivilegeSet;
use crate::resource::{Resource, ResourceService}; use crate::resource::{Resource, ResourceService};
use actix_web::dev::ResourceMap; use actix_web::dev::ResourceMap;
use actix_web::HttpRequest;
use async_trait::async_trait; use async_trait::async_trait;
use rustical_store::auth::User; use rustical_store::auth::User;
use rustical_xml::{XmlDeserialize, XmlSerialize}; use rustical_xml::{XmlDeserialize, XmlSerialize};
@@ -61,9 +60,14 @@ impl<PR: Resource> Resource for RootResource<PR> {
} }
} }
#[derive(Default)]
pub struct RootResourceService<PR: Resource>(PhantomData<PR>); pub struct RootResourceService<PR: Resource>(PhantomData<PR>);
impl<PR: Resource> Default for RootResourceService<PR> {
fn default() -> Self {
Self(PhantomData)
}
}
#[async_trait(?Send)] #[async_trait(?Send)]
impl<PR: Resource> ResourceService for RootResourceService<PR> { impl<PR: Resource> ResourceService for RootResourceService<PR> {
type PathComponents = (); type PathComponents = ();
@@ -71,14 +75,7 @@ impl<PR: Resource> ResourceService for RootResourceService<PR> {
type Resource = RootResource<PR>; type Resource = RootResource<PR>;
type Error = PR::Error; type Error = PR::Error;
async fn new( async fn get_resource(&self, _: &()) -> Result<Self::Resource, Self::Error> {
_req: &HttpRequest,
_path_components: Self::PathComponents,
) -> Result<Self, Self::Error> {
Ok(Self(Default::default()))
}
async fn get_resource(&self) -> Result<Self::Resource, Self::Error> {
Ok(RootResource::<PR>::default()) Ok(RootResource::<PR>::default())
} }
} }