0
0
Fork 0
mirror of https://git.verdigado.com/NB-Public/simple-wkd.git synced 2024-12-05 03:12:50 +01:00

Improve logging

This commit is contained in:
Delta1925 2023-04-19 00:25:40 +02:00
parent 7434766800
commit 18f814dec9
No known key found for this signature in database
GPG key ID: 1C21ACE44193CB25
6 changed files with 45 additions and 22 deletions

View file

@ -1,6 +1,6 @@
use chrono::Utc; use chrono::Utc;
use lettre::message::header::ContentType; use lettre::message::header::ContentType;
use log::{warn, debug}; use log::{debug, error, warn};
use crate::errors::SpecialErrors; use crate::errors::SpecialErrors;
use crate::management::{delete_key, Action, Pending}; use crate::management::{delete_key, Action, Pending};
@ -15,10 +15,11 @@ use std::path::Path;
pub fn confirm_action(token: &str) -> Result<(Action, String)> { pub fn confirm_action(token: &str) -> Result<(Action, String)> {
let pending_path = pending_path().join(token); let pending_path = pending_path().join(token);
let content = read_file(&pending_path)?; let content = log_err!(read_file(&pending_path), debug)?;
let key = log_err!(toml::from_str::<Pending>(&content), warn)?; let key = log_err!(toml::from_str::<Pending>(&content), warn)?;
if Utc::now().timestamp() - key.timestamp() > SETTINGS.max_age { if Utc::now().timestamp() - key.timestamp() > SETTINGS.max_age {
log_err!(fs::remove_file(&pending_path), warn)?; log_err!(fs::remove_file(&pending_path), warn)?;
debug!("Token {} was stale", token);
Err(SpecialErrors::ExpiredRequest)? Err(SpecialErrors::ExpiredRequest)?
} else { } else {
let address = match key.action() { let address = match key.action() {
@ -43,7 +44,11 @@ pub fn confirm_action(token: &str) -> Result<(Action, String)> {
} }
pub fn send_confirmation_email(address: &str, action: &Action, token: &str) -> Result<()> { pub fn send_confirmation_email(address: &str, action: &Action, token: &str) -> Result<()> {
let template = read_file(&Path::new("assets").join("mail-template.html"))?; let template = log_err!(
read_file(&Path::new("assets").join("mail-template.html")),
error,
true
)?;
let mut url = SETTINGS let mut url = SETTINGS
.external_url .external_url
.join("api/") .join("api/")
@ -77,8 +82,8 @@ pub fn send_confirmation_email(address: &str, action: &Action, token: &str) -> R
let email = log_err!(email, warn)?; let email = log_err!(email, warn)?;
match log_err!(MAILER.send(&email), warn){ match log_err!(MAILER.send(&email), warn) {
Ok(_) => Ok(()), Ok(_) => Ok(()),
Err(_) => Err(SpecialErrors::MailErr)? Err(_) => Err(SpecialErrors::MailErr)?,
} }
} }

View file

@ -22,7 +22,7 @@ macro_rules! log_err {
}}; }};
($var: expr, $level: ident, $panic: expr) => {{ ($var: expr, $level: ident, $panic: expr) => {{
let test = $var; let test = $var;
if log_err!(test, $level).is_err() { if log_err!(&test, $level).is_err() {
if $panic == true { if $panic == true {
panic!("{} {}", $crate::settings::ERROR_TEXT, test.unwrap_err()); panic!("{} {}", $crate::settings::ERROR_TEXT, test.unwrap_err());
} else { } else {

View file

@ -10,7 +10,8 @@ use crate::errors::SpecialErrors;
use crate::management::{clean_stale, store_pending_addition, store_pending_deletion, Action}; use crate::management::{clean_stale, store_pending_addition, store_pending_deletion, Action};
use crate::settings::{ROOT_FOLDER, SETTINGS}; use crate::settings::{ROOT_FOLDER, SETTINGS};
use crate::utils::{ use crate::utils::{
gen_random_token, get_email_from_cert, is_email_allowed, parse_pem, read_file, return_outcome, key_exists, gen_random_token, get_email_from_cert, is_email_allowed, key_exists, parse_pem, read_file,
return_outcome,
}; };
use actix_files::Files; use actix_files::Files;
@ -70,7 +71,6 @@ async fn main() -> std::io::Result<()> {
}) })
.bind((SETTINGS.bind_host.to_string(), SETTINGS.port))? .bind((SETTINGS.bind_host.to_string(), SETTINGS.port))?
.run(); .run();
debug!("Server started successfully!");
info!( info!(
"Listening on: {}:{} (External url: {})", "Listening on: {}:{} (External url: {})",
SETTINGS.bind_host, SETTINGS.port, SETTINGS.external_url SETTINGS.bind_host, SETTINGS.port, SETTINGS.external_url
@ -87,7 +87,7 @@ async fn index(req: HttpRequest) -> Result<HttpResponse, CompatErr> {
path.join(file) path.join(file)
}; };
if path.is_file() { if path.is_file() {
let template = read_file(&path)?; let template = log_err!(read_file(&path), error, true)?;
let page = template.replace("((%u))", SETTINGS.external_url.as_ref()); let page = template.replace("((%u))", SETTINGS.external_url.as_ref());
return Ok(HttpResponseBuilder::new(StatusCode::OK) return Ok(HttpResponseBuilder::new(StatusCode::OK)
.insert_header(ContentType::html()) .insert_header(ContentType::html())
@ -106,7 +106,10 @@ async fn submit(pem: web::Form<Key>) -> Result<HttpResponse, CompatErr> {
is_email_allowed(&email)?; is_email_allowed(&email)?;
let token = gen_random_token(); let token = gen_random_token();
store_pending_addition(pem.key.clone(), &email, &token)?; store_pending_addition(pem.key.clone(), &email, &token)?;
debug!("Sending email to {} to add a key... (Request token: {})", email, token); debug!(
"Sending email to {} to add a key... (Request token: {})",
email, token
);
send_confirmation_email(&email, &Action::Add, &token)?; send_confirmation_email(&email, &Action::Add, &token)?;
info!("User {} requested to add a key successfully!", email); info!("User {} requested to add a key successfully!", email);
Ok(return_outcome(Ok("You submitted your key successfully!"))?) Ok(return_outcome(Ok("You submitted your key successfully!"))?)
@ -116,7 +119,11 @@ async fn submit(pem: web::Form<Key>) -> Result<HttpResponse, CompatErr> {
async fn confirm(token: web::Query<Token>) -> Result<HttpResponse, CompatErr> { async fn confirm(token: web::Query<Token>) -> Result<HttpResponse, CompatErr> {
debug!("Handling token {}...", token.token); debug!("Handling token {}...", token.token);
let (action, email) = confirm_action(&token.token)?; let (action, email) = confirm_action(&token.token)?;
info!("User {} confirmed to {} his key successfully!", email, action.to_string().to_lowercase()); info!(
"User {} confirmed to {} his key successfully!",
email,
action.to_string().to_lowercase()
);
match action { match action {
Action::Add => Ok(return_outcome(Ok("Your key was added successfully!"))?), Action::Add => Ok(return_outcome(Ok("Your key was added successfully!"))?),
Action::Delete => Ok(return_outcome(Ok("Your key was deleted successfully!"))?), Action::Delete => Ok(return_outcome(Ok("Your key was deleted successfully!"))?),
@ -125,13 +132,19 @@ async fn confirm(token: web::Query<Token>) -> Result<HttpResponse, CompatErr> {
#[get("/api/delete")] #[get("/api/delete")]
async fn delete(email: web::Query<Email>) -> Result<HttpResponse, CompatErr> { async fn delete(email: web::Query<Email>) -> Result<HttpResponse, CompatErr> {
debug!("Handling user {} request to add a key...", email.email); debug!("Handling user {} request to delete a key...", email.email);
key_exists(&email.email)?; key_exists(&email.email)?;
let token = gen_random_token(); let token = gen_random_token();
store_pending_deletion(email.email.clone(), &token)?; store_pending_deletion(email.email.clone(), &token)?;
debug!("Sending email to {} to add a key... (Request token: {})", email.email, token); debug!(
"Sending email to {} to delete a key... (Request token: {})",
email.email, token
);
send_confirmation_email(&email.email, &Action::Delete, &token)?; send_confirmation_email(&email.email, &Action::Delete, &token)?;
info!("User {} requested to delete his key successfully!", email.email); info!(
"User {} requested to delete his key successfully!",
email.email
);
Ok(return_outcome(Ok( Ok(return_outcome(Ok(
"You requested the deletion of your key successfully!", "You requested the deletion of your key successfully!",
))?) ))?)

View file

@ -77,7 +77,8 @@ pub fn clean_stale(max_age: i64) {
let file_path = path.path(); let file_path = path.path();
let content = match read_file(&file_path) { let content = match read_file(&file_path) {
Ok(content) => content, Ok(content) => content,
Err(_) => { Err(error) => {
warn!("{} {}", ERROR_TEXT, error);
continue; continue;
} }
}; };

View file

@ -1,5 +1,5 @@
use lettre::{transport::smtp::authentication::Credentials, SmtpTransport}; use lettre::{transport::smtp::authentication::Credentials, SmtpTransport};
use log::error; use log::{debug, error, warn};
use once_cell::sync::Lazy; use once_cell::sync::Lazy;
use sequoia_net::wkd::Variant; use sequoia_net::wkd::Variant;
use sequoia_openpgp::policy::StandardPolicy; use sequoia_openpgp::policy::StandardPolicy;
@ -47,15 +47,18 @@ pub enum SMTPEncryption {
} }
fn get_settings() -> Settings { fn get_settings() -> Settings {
debug!("Parsing settings...");
let content = match read_file(&PathBuf::from("config.toml")) { let content = match read_file(&PathBuf::from("config.toml")) {
Ok(content) => content, Ok(content) => content,
Err(_) => { Err(_) => {
error!("Unable to access settings file!");
panic!("Unable to access settings file!") panic!("Unable to access settings file!")
} }
}; };
let settings = match log_err!(toml::from_str(&content), error) { let settings = match log_err!(toml::from_str(&content), error) {
Ok(settings) => settings, Ok(settings) => settings,
Err(_) => { Err(_) => {
error!("Unable to parse settings from file!");
panic!("Unable to parse settings from file!") panic!("Unable to parse settings from file!")
} }
}; };
@ -63,6 +66,7 @@ fn get_settings() -> Settings {
} }
fn get_mailer() -> SmtpTransport { fn get_mailer() -> SmtpTransport {
debug!("Setting up smtp...");
let creds = Credentials::new( let creds = Credentials::new(
SETTINGS.mail_settings.smtp_username.to_owned(), SETTINGS.mail_settings.smtp_username.to_owned(),
SETTINGS.mail_settings.smtp_password.to_owned(), SETTINGS.mail_settings.smtp_password.to_owned(),
@ -76,13 +80,15 @@ fn get_mailer() -> SmtpTransport {
let mailer = match builder { let mailer = match builder {
Ok(builder) => builder, Ok(builder) => builder,
Err(_) => { Err(_) => {
error!("Unable to set up smtp");
panic!("Unable to set up smtp") panic!("Unable to set up smtp")
} }
} }
.credentials(creds) .credentials(creds)
.port(SETTINGS.mail_settings.smtp_port) .port(SETTINGS.mail_settings.smtp_port)
.build(); .build();
let _ = mailer.test_connection(); debug!("Testing smtp connection...");
let _ = log_err!(mailer.test_connection(), warn);
mailer mailer
} }

View file

@ -12,8 +12,7 @@ use actix_web::{
use anyhow::Result; use anyhow::Result;
use flexi_logger::{style, DeferredNow, FileSpec, FlexiLoggerError, Logger, LoggerHandle, Record}; use flexi_logger::{style, DeferredNow, FileSpec, FlexiLoggerError, Logger, LoggerHandle, Record};
use log::debug; use log::debug;
use log::trace; use log::error;
use log::warn;
use rand::{distributions::Alphanumeric, thread_rng, Rng}; use rand::{distributions::Alphanumeric, thread_rng, Rng};
use sequoia_net::wkd::Url; use sequoia_net::wkd::Url;
use sequoia_openpgp::{parse::Parse, Cert}; use sequoia_openpgp::{parse::Parse, Cert};
@ -42,9 +41,8 @@ pub fn webpage_path() -> PathBuf {
pub fn read_file(path: &PathBuf) -> Result<String> { pub fn read_file(path: &PathBuf) -> Result<String> {
if path.is_file() { if path.is_file() {
Ok(log_err!(fs::read_to_string(path), warn)?) Ok(fs::read_to_string(path)?)
} else { } else {
trace!("The requested file {} does not exist", path.display());
Err(SpecialErrors::MissingFile)? Err(SpecialErrors::MissingFile)?
} }
} }
@ -171,7 +169,7 @@ pub fn init_logger() -> Result<LoggerHandle, FlexiLoggerError> {
pub fn return_outcome(data: Result<&str, &CompatErr>) -> Result<HttpResponse> { pub fn return_outcome(data: Result<&str, &CompatErr>) -> Result<HttpResponse> {
let path = webpage_path().join("status").join("index.html"); let path = webpage_path().join("status").join("index.html");
let template = read_file(&path)?; let template = log_err!(read_file(&path), error, true)?;
let (page, message) = match data { let (page, message) = match data {
Ok(message) => (template.replace("((%s))", "Success!"), message.to_string()), Ok(message) => (template.replace("((%s))", "Success!"), message.to_string()),
Err(error) => (template.replace("((%s))", "Failure!"), error.to_string()), Err(error) => (template.replace("((%s))", "Failure!"), error.to_string()),