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

Improve mail text and add logger

This commit is contained in:
Delta1925 2023-04-14 16:33:59 +02:00
parent 1a85cb77fa
commit b717852376
No known key found for this signature in database
GPG key ID: 1C21ACE44193CB25
6 changed files with 96 additions and 11 deletions

40
Cargo.lock generated
View file

@ -760,6 +760,22 @@ dependencies = [
"miniz_oxide", "miniz_oxide",
] ]
[[package]]
name = "flexi_logger"
version = "0.25.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6eae57842a8221ef13f1f207632d786a175dd13bd8fbdc8be9d852f7c9cf1046"
dependencies = [
"chrono",
"glob",
"is-terminal",
"lazy_static",
"log",
"nu-ansi-term",
"regex",
"thiserror",
]
[[package]] [[package]]
name = "fnv" name = "fnv"
version = "1.0.7" version = "1.0.7"
@ -1436,6 +1452,16 @@ dependencies = [
"minimal-lexical", "minimal-lexical",
] ]
[[package]]
name = "nu-ansi-term"
version = "0.46.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "77a8165726e8236064dbb45459242600304b42a5ea24ee2948e18e023bf7ba84"
dependencies = [
"overload",
"winapi",
]
[[package]] [[package]]
name = "num-integer" name = "num-integer"
version = "0.1.45" version = "0.1.45"
@ -1515,6 +1541,12 @@ dependencies = [
"vcpkg", "vcpkg",
] ]
[[package]]
name = "overload"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b15813163c1d831bf4a13c3610c05c0d03b39feb07f7e09fa234dac9b15aaf39"
[[package]] [[package]]
name = "parking_lot" name = "parking_lot"
version = "0.12.1" version = "0.12.1"
@ -2012,7 +2044,9 @@ version = "0.1.0"
dependencies = [ dependencies = [
"actix-web", "actix-web",
"chrono", "chrono",
"flexi_logger",
"lettre", "lettre",
"log",
"once_cell", "once_cell",
"rand 0.8.5", "rand 0.8.5",
"sequoia-net", "sequoia-net",
@ -2022,6 +2056,7 @@ dependencies = [
"thiserror", "thiserror",
"tokio", "tokio",
"toml", "toml",
"url",
] ]
[[package]] [[package]]
@ -2116,9 +2151,9 @@ dependencies = [
[[package]] [[package]]
name = "termcolor" name = "termcolor"
version = "1.2.0" version = "1.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "be55cf8942feac5c765c2c993422806843c9a9a45d4d5c407ad6dd2ea95eb9b6" checksum = "bab24d30b911b2376f3a13cc2cd443142f0c81dda04c118693e35b3835757755"
dependencies = [ dependencies = [
"winapi-util", "winapi-util",
] ]
@ -2452,6 +2487,7 @@ dependencies = [
"form_urlencoded", "form_urlencoded",
"idna 0.3.0", "idna 0.3.0",
"percent-encoding", "percent-encoding",
"serde",
] ]
[[package]] [[package]]

View file

@ -8,7 +8,9 @@ edition = "2021"
[dependencies] [dependencies]
actix-web = "4.3.1" actix-web = "4.3.1"
chrono = "0.4.24" chrono = "0.4.24"
flexi_logger = "0.25.3"
lettre = "0.10.4" lettre = "0.10.4"
log = "0.4.17"
once_cell = "1.17.1" once_cell = "1.17.1"
rand = "0.8.5" rand = "0.8.5"
sequoia-net = "0.27.0" sequoia-net = "0.27.0"
@ -18,3 +20,4 @@ serde_json = "1.0.96"
thiserror = "1.0.40" thiserror = "1.0.40"
tokio = { version = "1.27.0", features = ["time"] } tokio = { version = "1.27.0", features = ["time"] }
toml = "0.7.3" toml = "0.7.3"
url = { version = "2.3.1", features = ["serde"] }

View file

@ -67,8 +67,23 @@ pub fn send_confirmation_email(email: &str, action: &Action, token: &str) -> Res
Ok(mailbox) => mailbox, Ok(mailbox) => mailbox,
Err(_) => return Err(Error::ParseEmail), Err(_) => return Err(Error::ParseEmail),
}) })
.subject(&SETTINGS.mail_settings.mail_subject) .subject(
.body(format!("{action} - {token}")); SETTINGS
.mail_settings
.mail_subject
.replace("%a", &action.to_string().to_lowercase()),
)
.body(format!(
"{}",
SETTINGS
.external_url
.join("api/")
.unwrap()
.join("confirm/")
.unwrap()
.join(token)
.unwrap()
));
let message = match email { let message = match email {
Ok(message) => message, Ok(message) => message,

View file

@ -12,10 +12,12 @@ use self::management::{clean_stale, store_pending_addition, store_pending_deleti
use self::utils::{gen_random_token, get_email_from_cert, parse_pem}; use self::utils::{gen_random_token, get_email_from_cert, parse_pem};
use actix_web::{get, post, web, App, HttpServer, Result}; use actix_web::{get, post, web, App, HttpServer, Result};
use log::error;
use serde::Deserialize; use serde::Deserialize;
use std::fs; use std::fs;
use std::path::Path; use std::path::Path;
use tokio::{task, time}; use tokio::{task, time};
use utils::init_logger;
const PENDING_FOLDER: &str = "pending"; const PENDING_FOLDER: &str = "pending";
@ -36,13 +38,16 @@ struct Email {
#[actix_web::main] #[actix_web::main]
async fn main() -> std::io::Result<()> { async fn main() -> std::io::Result<()> {
if init_logger().is_err() {
panic!("Could not set up logger!")
};
fs::create_dir_all(pending_path!())?; fs::create_dir_all(pending_path!())?;
task::spawn(async { task::spawn(async {
let mut metronome = time::interval(time::Duration::from_secs(SETTINGS.cleanup_interval)); let mut metronome = time::interval(time::Duration::from_secs(SETTINGS.cleanup_interval));
loop { loop {
metronome.tick().await; metronome.tick().await;
if clean_stale(SETTINGS.max_age).is_err() { if clean_stale(SETTINGS.max_age).is_err() {
eprintln!("Error while cleaning stale requests..."); error!("Error while cleaning stale requests!");
} }
} }
}); });

View file

@ -3,6 +3,7 @@ use once_cell::sync::Lazy;
use sequoia_net::wkd::Variant; use sequoia_net::wkd::Variant;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::fs; use std::fs;
use url::Url;
#[derive(Serialize, Deserialize, Debug)] #[derive(Serialize, Deserialize, Debug)]
pub struct Settings { pub struct Settings {
@ -12,7 +13,7 @@ pub struct Settings {
pub max_age: i64, pub max_age: i64,
pub cleanup_interval: u64, pub cleanup_interval: u64,
pub port: u16, pub port: u16,
pub external_url: String, pub external_url: Url,
pub mail_settings: MailSettings, pub mail_settings: MailSettings,
} }
@ -41,15 +42,15 @@ pub enum SMTPEncryption {
} }
fn get_settings() -> Settings { fn get_settings() -> Settings {
println!("Reading settings...");
let content = match fs::read_to_string("wkd.toml") { let content = match fs::read_to_string("wkd.toml") {
Ok(content) => content, Ok(content) => content,
Err(_) => panic!("Unable to access settings file!"), Err(_) => panic!("Unable to access settings file!"),
}; };
match toml::from_str(&content) { let settings = match toml::from_str(&content) {
Ok(settings) => settings, Ok(settings) => settings,
Err(_) => panic!("Unable to parse settings from file!"), Err(_) => panic!("Unable to parse settings from file!"),
} };
settings
} }
fn get_mailer() -> SmtpTransport { fn get_mailer() -> SmtpTransport {
@ -63,13 +64,14 @@ fn get_mailer() -> SmtpTransport {
SmtpTransport::starttls_relay(&SETTINGS.mail_settings.smtp_host) SmtpTransport::starttls_relay(&SETTINGS.mail_settings.smtp_host)
} }
}; };
match builder { let mailer = match builder {
Ok(builder) => builder, Ok(builder) => builder,
Err(_) => panic!("Unable to set up smtp"), Err(_) => panic!("Unable to set up smtp"),
} }
.credentials(creds) .credentials(creds)
.port(SETTINGS.mail_settings.smtp_port) .port(SETTINGS.mail_settings.smtp_port)
.build() .build();
mailer
} }
pub static SETTINGS: Lazy<Settings> = Lazy::new(get_settings); pub static SETTINGS: Lazy<Settings> = Lazy::new(get_settings);

View file

@ -1,6 +1,7 @@
use crate::errors::Error; use crate::errors::Error;
use crate::settings::SETTINGS; use crate::settings::SETTINGS;
use flexi_logger::{style, DeferredNow, FlexiLoggerError, Logger, LoggerHandle, Record};
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};
@ -58,3 +59,26 @@ pub fn key_exists(email: &str) -> Result<bool, Error> {
} }
Ok(true) Ok(true)
} }
pub fn custom_format(
w: &mut dyn std::io::Write,
now: &mut DeferredNow,
record: &Record,
) -> Result<(), std::io::Error> {
let level = record.level();
write!(
w,
"[{}] [{}] {}: {}",
style(level).paint(now.format("%Y-%m-%d %H:%M:%S").to_string()),
style(level).paint(record.module_path().unwrap_or("<unnamed>")),
style(level).paint(record.level().to_string()),
style(level).paint(&record.args().to_string())
)
}
pub fn init_logger() -> Result<LoggerHandle, FlexiLoggerError> {
Logger::try_with_env_or_str("simple_wkd=trace")?
.format(custom_format)
.set_palette("b1;3;2;4;6".to_string())
.start()
}