Add img protection

This commit is contained in:
Rémi BERTHO 2023-12-14 13:43:33 +01:00
parent 1681188214
commit 90d0eacca6
Signed by: dalan
GPG Key ID: EE3B917931C07B64
3 changed files with 294 additions and 189 deletions

455
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -13,4 +13,6 @@ rust-embed = "8"
directories = "5"
clap = "4"
warp = "0.3"
tokio = { version = "1", features = ["full"] }
tokio = { version = "1", features = ["full"] }
portpicker = "0.1"
rand = "0.8"

View File

@ -4,6 +4,7 @@ use anyhow::{anyhow, bail, Result};
use clap::{Arg, Command};
use log::info;
use native_dialog::{FileDialog, MessageDialog};
use rand::distributions::{DistString};
use rust_embed::RustEmbed;
use simplelog::{ColorChoice, ConfigBuilder, LevelFilter, TermLogger, TerminalMode};
use std::{borrow::Cow, path::PathBuf, thread::JoinHandle};
@ -77,7 +78,9 @@ fn main() -> Result<()> {
}
info!("Run server");
run_server(img_path.to_path_buf());
let port = portpicker::pick_unused_port().ok_or_else(|| anyhow!("Cannot find ununsed port"))?;
let user_agent = rand::distributions::Alphanumeric.sample_string(&mut rand::thread_rng(), 32);
run_server(img_path.to_path_buf(), port, user_agent.clone());
info!("Create webview");
let event_loop = EventLoop::new();
@ -87,7 +90,8 @@ fn main() -> Result<()> {
.build(&event_loop)?;
let data_dir = directories::ProjectDirs::from("fr", "dalan", "SimplePanoramaViwer").unwrap();
let _webview = WebViewBuilder::new(window)?
.with_url("http://127.0.0.1:62371/index.html")?
.with_url(&format!("http://127.0.0.1:{}/index.html", port))?
.with_user_agent(&user_agent)
.with_web_context(&mut WebContext::new(Some(
data_dir.cache_dir().to_path_buf(),
)))
@ -111,8 +115,8 @@ fn main() -> Result<()> {
});
}
fn run_server(img_path: PathBuf) -> JoinHandle<()> {
std::thread::spawn(|| {
fn run_server(img_path: PathBuf, port: u16, user_agent: String) -> JoinHandle<()> {
std::thread::spawn(move || {
info!("Create runtime");
let async_runtime = tokio::runtime::Builder::new_current_thread()
.enable_all()
@ -134,10 +138,18 @@ fn run_server(img_path: PathBuf) -> JoinHandle<()> {
let datas = get_file_data(&format!("js/{}", val));
warp::http::Response::builder().body(datas)
});
let img = warp::path!("img").map(move || std::fs::read(&img_path).unwrap());
let img = warp::path!("img")
.and(warp::header("user-agent"))
.map(move |agent: String| {
if agent == user_agent {
std::fs::read(&img_path).unwrap()
} else {
Vec::new()
}
});
info!("Launch webserver");
async_runtime
.block_on(warp::serve(img.or(index).or(css).or(js)).run(([127, 0, 0, 1], 62371)));
.block_on(warp::serve(img.or(index).or(css).or(js)).run(([127, 0, 0, 1], port)));
})
}