Compare commits

..

No commits in common. "d878f4e82c6f802be0d909df1f505345e8729332" and "07b8bb7bfef61a69d6acc6b7f1c3bfdd65dd40a9" have entirely different histories.

6 changed files with 43 additions and 70 deletions

View File

@ -134,25 +134,6 @@ pub async fn handle_upload(
} }
} }
pub async fn handle_delete(
app: App,
token: SessionToken,
id: FileId,
) -> Result<http::Response<String>, Error> {
match app.validate_session(token).await {
Ok(Some(_)) => match app.delete_file(id).await {
Ok(_) => Response::builder()
.header("location", "/")
.status(StatusCode::SEE_OTHER)
.body("".to_owned()),
Err(_) => unimplemented!(),
},
_ => Response::builder()
.status(StatusCode::UNAUTHORIZED)
.body("".to_owned()),
}
}
fn serve_file<F>( fn serve_file<F>(
info: FileInfo, info: FileInfo,
file: F, file: F,

View File

@ -74,7 +74,7 @@ impl Html for Form {
None => "".to_owned(), None => "".to_owned(),
}; };
format!( format!(
"<form action=\"{path}\" method=\"{method}\" {encoding}>\n{elements}\n</form>\n", "<form action=\"{path}\" method=\"{method}\" {encoding}\n{elements}\n</form>\n",
path = self.path, path = self.path,
method = self.method, method = self.method,
encoding = encoding, encoding = encoding,
@ -137,6 +137,11 @@ impl Input {
self self
} }
pub fn with_value(mut self, val: &str) -> Self {
self.value = Some(val.to_owned());
self
}
pub fn with_attributes<'a>( pub fn with_attributes<'a>(
mut self, mut self,
values: impl IntoIterator<Item = (&'a str, &'a str)>, values: impl IntoIterator<Item = (&'a str, &'a str)>,
@ -151,6 +156,31 @@ impl Input {
} }
} }
#[derive(Clone, Debug)]
pub struct Label {
target: String,
text: String,
}
impl Label {
pub fn new(target: &str, text: &str) -> Self {
Self {
target: target.to_owned(),
text: text.to_owned(),
}
}
}
impl Html for Label {
fn to_html_string(&self) -> String {
format!(
"<label for=\"{target}\">{text}</label>",
target = self.target,
text = self.text
)
}
}
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub struct Button { pub struct Button {
ty: Option<String>, ty: Option<String>,

View File

@ -1,6 +1,6 @@
mod store; mod store;
pub use store::{ pub use store::{
AuthDB, AuthError, AuthToken, DeleteFileError, FileHandle, FileId, FileInfo, ReadFileError, AuthDB, AuthError, AuthToken, FileHandle, FileId, FileInfo, ReadFileError, SessionToken, Store,
SessionToken, Store, Username, WriteFileError, Username, WriteFileError,
}; };

View File

@ -1,7 +1,7 @@
extern crate log; extern crate log;
use cookie::Cookie; use cookie::Cookie;
use handlers::{file, handle_auth, handle_css, handle_delete, handle_upload, thumbnail}; use handlers::{file, handle_auth, handle_css, handle_upload, thumbnail};
use std::{ use std::{
collections::{HashMap, HashSet}, collections::{HashMap, HashSet},
convert::Infallible, convert::Infallible,
@ -19,8 +19,8 @@ mod pages;
const MAX_UPLOAD: u64 = 15 * 1024 * 1024; const MAX_UPLOAD: u64 = 15 * 1024 * 1024;
pub use file_service::{ pub use file_service::{
AuthDB, AuthError, AuthToken, DeleteFileError, FileHandle, FileId, FileInfo, ReadFileError, AuthDB, AuthError, AuthToken, FileHandle, FileId, FileInfo, ReadFileError, SessionToken, Store,
SessionToken, Store, Username, WriteFileError, Username, WriteFileError,
}; };
pub use handlers::handle_index; pub use handlers::handle_index;
@ -64,11 +64,6 @@ impl App {
) -> Result<FileHandle, WriteFileError> { ) -> Result<FileHandle, WriteFileError> {
self.store.write().await.add_file(filename, content) self.store.write().await.add_file(filename, content)
} }
pub async fn delete_file(&self, id: FileId) -> Result<(), DeleteFileError> {
self.store.write().await.delete_file(&id)?;
Ok(())
}
} }
fn with_app(app: App) -> impl Filter<Extract = (App,), Error = Infallible> + Clone { fn with_app(app: App) -> impl Filter<Extract = (App,), Error = Infallible> + Clone {
@ -139,12 +134,6 @@ pub async fn main() {
.and(warp::multipart::form().max_length(MAX_UPLOAD)) .and(warp::multipart::form().max_length(MAX_UPLOAD))
.then(handle_upload); .then(handle_upload);
let delete_via_form = warp::path!("delete" / String)
.and(warp::post())
.and(with_app(app.clone()))
.and(with_session())
.then(|id, app, token| handle_delete(app, token, FileId::from(id)));
let thumbnail = warp::path!(String / "tn") let thumbnail = warp::path!(String / "tn")
.and(warp::get()) .and(warp::get())
.and(warp::header::optional::<String>("if-none-match")) .and(warp::header::optional::<String>("if-none-match"))
@ -161,7 +150,6 @@ pub async fn main() {
root.or(styles) root.or(styles)
.or(auth) .or(auth)
.or(upload_via_form) .or(upload_via_form)
.or(delete_via_form)
.or(thumbnail) .or(thumbnail)
.or(file) .or(file)
.with(log), .with(log),

View File

@ -92,7 +92,7 @@ pub fn thumbnail(info: &FileInfo) -> Container {
format!("/{}", *info.id), format!("/{}", *info.id),
Container::default() Container::default()
.with_attributes([("class", "thumbnail")]) .with_attributes([("class", "thumbnail")])
.with_image(format!("{}/tn", *info.id), "test data") .with_image(&format!("{}/tn", *info.id), "test data")
.to_html_string(), .to_html_string(),
), ),
) )
@ -106,8 +106,9 @@ pub fn thumbnail(info: &FileInfo) -> Container {
) )
.with_html( .with_html(
Form::new() Form::new()
.with_path(&format!("/delete/{}", *info.id)) .with_path(&format!("/{}", *info.id))
.with_method("post") .with_method("post")
.with_html(Input::new("hidden", "_method").with_value("delete"))
.with_html(Button::new("Delete")), .with_html(Button::new("Delete")),
), ),
) )

View File

@ -53,6 +53,9 @@ pub enum ReadFileError {
#[error("permission denied")] #[error("permission denied")]
PermissionDenied, PermissionDenied,
#[error("invalid path")]
InvalidPath,
#[error("JSON error")] #[error("JSON error")]
JSONError(#[from] serde_json::error::Error), JSONError(#[from] serde_json::error::Error),
@ -60,36 +63,6 @@ pub enum ReadFileError {
IOError(#[from] std::io::Error), IOError(#[from] std::io::Error),
} }
#[derive(Debug, Error)]
pub enum DeleteFileError {
#[error("file not found")]
FileNotFound(PathBuf),
#[error("metadata path is not a file")]
NotAFile,
#[error("cannot read metadata")]
PermissionDenied,
#[error("invalid metadata path")]
MetadataParseError(serde_json::error::Error),
#[error("IO error")]
IOError(#[from] std::io::Error),
}
impl From<ReadFileError> for DeleteFileError {
fn from(err: ReadFileError) -> Self {
match err {
ReadFileError::FileNotFound(path) => DeleteFileError::FileNotFound(path),
ReadFileError::NotAFile => DeleteFileError::NotAFile,
ReadFileError::PermissionDenied => DeleteFileError::PermissionDenied,
ReadFileError::JSONError(err) => DeleteFileError::MetadataParseError(err),
ReadFileError::IOError(err) => DeleteFileError::IOError(err),
}
}
}
#[derive(Debug, Error)] #[derive(Debug, Error)]
pub enum AuthError { pub enum AuthError {
#[error("authentication token is duplicated")] #[error("authentication token is duplicated")]
@ -396,7 +369,7 @@ impl Store {
FileHandle::load(id, &self.files_root) FileHandle::load(id, &self.files_root)
} }
pub fn delete_file(&mut self, id: &FileId) -> Result<(), DeleteFileError> { pub fn delete_file(&mut self, id: &FileId) -> Result<(), WriteFileError> {
let handle = FileHandle::load(id, &self.files_root)?; let handle = FileHandle::load(id, &self.files_root)?;
handle.delete(); handle.delete();
Ok(()) Ok(())