monorepo/file-service/src/main.rs

175 lines
5.2 KiB
Rust
Raw Normal View History

extern crate log;
use cookie::Cookie;
2023-10-26 02:54:05 +00:00
use handlers::{file, handle_auth, handle_css, handle_delete, handle_upload, thumbnail};
use std::{
collections::{HashMap, HashSet},
2023-10-03 15:10:37 +00:00
convert::Infallible,
net::{IpAddr, Ipv4Addr, SocketAddr},
path::PathBuf,
2023-10-03 20:18:19 +00:00
sync::Arc,
};
2023-10-03 20:18:19 +00:00
use tokio::sync::RwLock;
2023-10-05 04:08:27 +00:00
use warp::{Filter, Rejection};
2023-10-03 15:10:37 +00:00
mod handlers;
mod html;
mod pages;
2023-10-05 04:08:27 +00:00
const MAX_UPLOAD: u64 = 15 * 1024 * 1024;
use authdb::{AuthDB, AuthError, AuthToken, SessionToken, Username};
use file_service::{
DeleteFileError, FileHandle, FileId, FileInfo, ReadFileError, Store, WriteFileError,
};
2023-10-03 20:18:19 +00:00
pub use handlers::handle_index;
2023-10-03 20:18:19 +00:00
#[derive(Clone)]
pub struct App {
authdb: Arc<RwLock<AuthDB>>,
store: Arc<RwLock<Store>>,
}
impl App {
pub fn new(authdb: AuthDB, store: Store) -> Self {
Self {
authdb: Arc::new(RwLock::new(authdb)),
store: Arc::new(RwLock::new(store)),
}
}
pub async fn authenticate(&self, token: AuthToken) -> Result<Option<SessionToken>, AuthError> {
self.authdb.read().await.authenticate(token).await
2023-10-03 20:18:19 +00:00
}
pub async fn validate_session(
&self,
token: SessionToken,
) -> Result<Option<Username>, AuthError> {
self.authdb.read().await.validate_session(token).await
2023-10-03 20:18:19 +00:00
}
pub async fn list_files(&self) -> Result<HashSet<FileId>, ReadFileError> {
self.store.read().await.list_files()
}
pub async fn get_file(&self, id: &FileId) -> Result<FileHandle, ReadFileError> {
self.store.read().await.get_file(id)
}
pub async fn add_file(
&self,
filename: String,
content: Vec<u8>,
) -> Result<FileHandle, WriteFileError> {
self.store.write().await.add_file(filename, content)
}
2023-10-26 02:54:05 +00:00
pub async fn delete_file(&self, id: FileId) -> Result<(), DeleteFileError> {
self.store.write().await.delete_file(&id)?;
Ok(())
}
2023-10-03 20:18:19 +00:00
}
2023-10-03 15:10:37 +00:00
fn with_app(app: App) -> impl Filter<Extract = (App,), Error = Infallible> + Clone {
warp::any().map(move || app.clone())
}
fn parse_cookies(cookie_str: &str) -> Result<HashMap<String, String>, cookie::ParseError> {
Cookie::split_parse(cookie_str)
.map(|c| c.map(|c| (c.name().to_owned(), c.value().to_owned())))
.collect::<Result<HashMap<String, String>, cookie::ParseError>>()
}
fn get_session_token(cookies: HashMap<String, String>) -> Option<SessionToken> {
2023-10-04 19:57:18 +00:00
cookies.get("session").cloned().map(SessionToken::from)
}
2023-10-03 15:10:37 +00:00
fn maybe_with_session() -> impl Filter<Extract = (Option<SessionToken>,), Error = Rejection> + Copy
{
warp::any()
.and(warp::header::optional::<String>("cookie"))
.map(|cookie_str: Option<String>| match cookie_str {
Some(cookie_str) => parse_cookies(&cookie_str).ok().and_then(get_session_token),
None => None,
2023-10-03 15:10:37 +00:00
})
}
2023-10-03 15:10:37 +00:00
fn with_session() -> impl Filter<Extract = (SessionToken,), Error = Rejection> + Copy {
warp::any()
.and(warp::header::<String>("cookie"))
.and_then(|cookie_str: String| async move {
match parse_cookies(&cookie_str).ok().and_then(get_session_token) {
Some(session_token) => Ok(session_token),
None => Err(warp::reject()),
}
})
2023-10-03 15:10:37 +00:00
}
2023-10-03 15:10:37 +00:00
#[tokio::main]
pub async fn main() {
pretty_env_logger::init();
let authdb = AuthDB::new(PathBuf::from(&std::env::var("AUTHDB").unwrap()))
.await
.unwrap();
2023-10-03 15:10:37 +00:00
let store = Store::new(PathBuf::from(&std::env::var("FILE_SHARE_DIR").unwrap()));
2023-10-03 15:10:37 +00:00
let app = App::new(authdb, store);
let log = warp::log("file_service");
2023-10-03 15:10:37 +00:00
let root = warp::path!()
.and(warp::get())
.and(with_app(app.clone()))
.and(maybe_with_session())
.then(handle_index);
2023-10-06 23:04:15 +00:00
let styles = warp::path!("css").and(warp::get()).then(handle_css);
2023-10-03 15:10:37 +00:00
let auth = warp::path!("auth")
2023-09-27 02:43:33 +00:00
.and(warp::post())
.and(with_app(app.clone()))
2023-10-03 15:10:37 +00:00
.and(warp::filters::body::form())
.then(handle_auth);
2023-09-27 02:43:33 +00:00
let upload_via_form = warp::path!("upload")
.and(warp::post())
2023-10-03 15:10:37 +00:00
.and(with_app(app.clone()))
.and(with_session())
2023-10-05 04:08:27 +00:00
.and(warp::multipart::form().max_length(MAX_UPLOAD))
2023-10-03 15:10:37 +00:00
.then(handle_upload);
2023-10-26 02:54:05 +00:00
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)));
2023-09-21 04:00:09 +00:00
let thumbnail = warp::path!(String / "tn")
.and(warp::get())
2023-09-21 04:00:09 +00:00
.and(warp::header::optional::<String>("if-none-match"))
2023-10-03 15:10:37 +00:00
.and(with_app(app.clone()))
.then(move |id, old_etags, app: App| thumbnail(app, id, old_etags));
let file = warp::path!(String)
.and(warp::get())
.and(warp::header::optional::<String>("if-none-match"))
2023-10-03 15:10:37 +00:00
.and(with_app(app.clone()))
.then(move |id, old_etags, app: App| file(app, id, old_etags));
2023-09-21 03:31:52 +00:00
let server = warp::serve(
2023-10-06 23:04:15 +00:00
root.or(styles)
.or(auth)
.or(upload_via_form)
2023-10-26 02:54:05 +00:00
.or(delete_via_form)
.or(thumbnail)
.or(file)
.with(log),
);
2023-10-03 15:10:37 +00:00
server
.run(SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), 8002))
.await;
}