WIP: Start implementing precondition errors

This commit is contained in:
Lennart
2025-06-04 20:03:30 +02:00
parent e57a14cad1
commit 1a827a164f
9 changed files with 239 additions and 167 deletions

View File

@@ -1,4 +1,5 @@
use crate::Error;
use crate::error::Precondition;
use actix_web::HttpRequest;
use actix_web::HttpResponse;
use actix_web::http::header;
@@ -60,16 +61,21 @@ pub async fn put_event<C: CalendarStore>(
} = path.into_inner();
if !user.is_principal(&principal) {
return Ok(HttpResponse::Unauthorized().body(""));
return Ok(HttpResponse::Unauthorized().finish());
}
let overwrite =
Some(&HeaderValue::from_static("*")) != req.headers().get(header::IF_NONE_MATCH);
let object = CalendarObject::from_ics(object_id, body)?;
let object = match CalendarObject::from_ics(object_id, body) {
Ok(obj) => obj,
Err(_) => {
return Err(Error::PreconditionFailed(Precondition::ValidCalendarData));
}
};
store
.put_object(principal, calendar_id, object, overwrite)
.await?;
Ok(HttpResponse::Created().body(""))
Ok(HttpResponse::Created().finish())
}

View File

@@ -1,6 +1,36 @@
use actix_web::{HttpResponse, http::StatusCode};
use actix_web::{
HttpResponse,
http::{StatusCode, header::ContentType},
};
use rustical_xml::{XmlSerialize, XmlSerializeRoot};
use tracing::error;
#[derive(Debug, thiserror::Error, XmlSerialize)]
pub enum Precondition {
#[error("valid-calendar-data")]
#[xml(ns = "rustical_dav::namespace::NS_CALDAV")]
ValidCalendarData,
}
impl actix_web::ResponseError for Precondition {
fn status_code(&self) -> StatusCode {
StatusCode::PRECONDITION_FAILED
}
fn error_response(&self) -> HttpResponse<actix_web::body::BoxBody> {
let mut output: Vec<_> = b"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n".into();
let mut writer = quick_xml::Writer::new_with_indent(&mut output, b' ', 4);
let error = rustical_dav::xml::ErrorElement(self);
if let Err(err) = error.serialize_root(&mut writer) {
return rustical_dav::Error::from(err).error_response();
}
HttpResponse::PreconditionFailed()
.content_type(ContentType::xml())
.body(String::from_utf8(output).unwrap())
}
}
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("Unauthorized")]
@@ -26,6 +56,9 @@ pub enum Error {
#[error(transparent)]
IcalError(#[from] rustical_ical::Error),
#[error(transparent)]
PreconditionFailed(Precondition),
}
impl actix_web::ResponseError for Error {
@@ -44,6 +77,7 @@ impl actix_web::ResponseError for Error {
Error::NotImplemented => StatusCode::INTERNAL_SERVER_ERROR,
Error::NotFound => StatusCode::NOT_FOUND,
Error::IcalError(err) => err.status_code(),
Error::PreconditionFailed(err) => err.status_code(),
}
}
fn error_response(&self) -> actix_web::HttpResponse<actix_web::body::BoxBody> {
@@ -51,6 +85,7 @@ impl actix_web::ResponseError for Error {
match self {
Error::DavError(err) => err.error_response(),
Error::IcalError(err) => err.error_response(),
Error::PreconditionFailed(err) => err.error_response(),
_ => HttpResponse::build(self.status_code()).body(self.to_string()),
}
}