update application configuration

This commit is contained in:
glyph 2022-03-24 09:07:43 +02:00
parent 1bdacf3632
commit 928afb35d3
1 changed files with 32 additions and 94 deletions

View File

@ -12,14 +12,11 @@
//! micro-web-framework), Maud (an HTML template engine for Rust), HTML and
//! CSS.
//mod context;
mod config;
pub mod error;
mod private_router;
mod public_router;
mod routes;
//#[cfg(test)]
//mod tests;
mod templates;
pub mod utils;
@ -29,96 +26,45 @@ use std::{
};
use lazy_static::lazy_static;
//use log::{debug, error, info};
use log::info;
//use peach_lib::{config_manager, config_manager::YAML_PATH as PEACH_CONFIG};
//use rocket::{fairing::AdHoc, serde::Deserialize, Build, Rocket};
use log::{debug, info};
use peach_lib::{config_manager, config_manager::YAML_PATH as PEACH_CONFIG};
// crate-local dependencies
use config::Config;
use utils::theme::Theme;
pub type BoxError = Box<dyn std::error::Error>;
/*
/// Application configuration parameters.
/// These values are extracted from Rocket's default configuration provider:
/// `Config::figment()`. As such, the values are drawn from `Rocket.toml` or
/// the TOML file path in the `ROCKET_CONFIG` environment variable. The TOML
/// file parameters are automatically overruled by any `ROCKET_` variables
/// which might be set.
#[derive(Debug, Deserialize)]
pub struct RocketConfig {
disable_auth: bool,
standalone_mode: bool,
}
*/
/// The path of the application configuration parameters.
static CONFIG_PATH: &str = "./config";
// load the application configuration and create the theme switcher
lazy_static! {
static ref CONFIG: Config = Config::from_file(CONFIG_PATH).expect("failed to read config file");
static ref CONFIG: Config = Config::new();
static ref THEME: RwLock<Theme> = RwLock::new(Theme::Light);
}
//static WLAN_IFACE: &str = "wlan0";
//static AP_IFACE: &str = "ap0";
/*
pub fn init_rocket() -> Rocket<Build> {
info!("Initializing Rocket");
// build a basic rocket instance
let rocket = rocket::build();
// return the default provider figment used by `rocket::build()`
let figment = rocket.figment();
// deserialize configuration parameters into our `RocketConfig` struct (defined above)
// since we're in the intialisation phase, panic if the extraction fails
let config: RocketConfig = figment.extract().expect("configuration extraction failed");
debug!("{:?}", config);
info!("Mounting Rocket routes");
let mounted_rocket = if config.standalone_mode {
router::mount_peachpub_routes(rocket)
} else {
router::mount_peachcloud_routes(rocket)
};
info!("Attaching application configuration to managed state");
mounted_rocket.attach(AdHoc::config::<RocketConfig>())
}
*/
/// Session data for each authenticated client.
#[derive(Debug, Clone)]
pub struct SessionData {
_login: String,
}
// TODO: parse these values from config file (or env var)
const HOSTNAME_AND_PORT: &str = "localhost:8000";
/// Launch the peach-web server.
fn main() {
// initialize logger
env_logger::init();
/*
// check if /var/lib/peachcloud/config.yml exists
if !std::path::Path::new(PEACH_CONFIG).exists() {
info!("PeachCloud configuration file not found; loading default values");
debug!("PeachCloud configuration file not found; loading default values");
// since we're in the intialisation phase, panic if the loading fails
let config =
config_manager::load_peach_config().expect("peachcloud configuration loading failed");
info!("Saving default PeachCloud configuration values to file");
debug!("Saving default PeachCloud configuration values to file");
// this ensures a config file is created if it does not already exist
config_manager::save_peach_config(config).expect("peachcloud configuration saving failed");
}
*/
// set ip address / hostname and port for the webserver
// defaults to "127.0.0.1:8000"
let addr_and_port = format!("{}:{}", CONFIG.addr, CONFIG.port);
// store the session data for each session and a hashmap that associates
// each session id with the data
@ -126,57 +72,49 @@ fn main() {
// the program is restarted.
let sessions_storage: Mutex<HashMap<String, SessionData>> = Mutex::new(HashMap::new());
info!("Launching web server...");
info!("Launching web server on {}", addr_and_port);
// the `start_server` starts listening forever on the given address
rouille::start_server(HOSTNAME_AND_PORT, move |request| {
info!("Now listening on {}", HOSTNAME_AND_PORT);
// We call `session::session` in order to assign a unique identifier
// to each client. This identifier is tracked through a cookie that
// is automatically appended to the response.
//
// The parameters of the function are the name of the cookie
// ("SID") and the duration of the session in seconds (one hour).
rouille::start_server(addr_and_port, move |request| {
// assign a unique id to each client (appends a cookie to the response
// with a name of "SID" and a duration of one hour (3600 seconds)
rouille::session::session(request, "SID", 3600, |session| {
// If the client already has an identifier from a previous request,
// we try to load the existing session data. If we successfully
// load data from `sessions_storage`, we make a copy of the data
// in order to avoid locking the session for too long.
//
// We thus obtain a `Option<SessionData>`.
// if the client already has an identifier from a previous request,
// try to load the existing session data. if successful, make a
// copy of the data in order to avoid locking the session for too
// long
let mut session_data = if session.client_has_sid() {
sessions_storage.lock().unwrap().get(session.id()).cloned()
} else {
None
};
// Pass the request to the public router.
// pass the request to the public router
//
// The public router includes authentication-related routes which
// the public router includes authentication-related routes which
// do not require the user to be authenticated (ie. login and reset
// password).
// password)
//
// If the user is already authenticated, their request will be
// passed to the private router by public_router::handle_route().
// if the user is already authenticated, their request will be
// passed to the private router by public_router::handle_route()
//
// We pass a mutable reference to the `Option<SessionData>` so that
// the function is free to modify it.
// we pass a mutable reference to the `Option<SessionData>` so that
// the function is free to modify it
let response = public_router::handle_route(request, &mut session_data);
// Since the function call to `handle_route` can modify the session
// data, we have to store it back in the `sessions_storage` when
// necessary.
// since the function call to `handle_route` can modify the session
// data, we have to store it back in the `sessions_storage` after
// the request has been handled
if let Some(data) = session_data {
sessions_storage
.lock()
.unwrap()
.insert(session.id().to_owned(), data);
} else if session.client_has_sid() {
// If `handle_route` erased the content of the `Option`, we
// remove the session from the storage. This is only done
// if the client already has an identifier, otherwise calling
// `session.id()` will assign one.
// if the content of the `Option` was erased (ie. due to
// deauthentication on logout), remove the session from the
// storage. this is only done if the client already has an
// identifier, otherwise calling `session.id()` will assign one
sessions_storage.lock().unwrap().remove(session.id());
}