0
0
Fork 0
mirror of https://git.verdigado.com/NB-Public/simple-wkd.git synced 2024-12-06 14:52:41 +01:00

Improve webpage

This commit is contained in:
Delta1925 2023-04-16 13:58:52 +02:00
parent d5cb622b9e
commit 4853519325
No known key found for this signature in database
GPG key ID: 1C21ACE44193CB25
12 changed files with 76 additions and 61 deletions

View file

@ -5,7 +5,7 @@ use log::{debug, error, trace, warn};
use crate::errors::Error;
use crate::management::{delete_key, Action, Pending};
use crate::pending_path;
use crate::settings::{MAILER, SETTINGS};
use crate::settings::{MAILER, ROOT_FOLDER, SETTINGS};
use crate::utils::{get_email_from_cert, get_filename, parse_pem};
use lettre::{Message, Transport};
@ -63,12 +63,7 @@ pub fn confirm_action(token: &str) -> Result<(Action, String), Error> {
return Err(Error::ParseEmail);
}
};
match sequoia_net::wkd::insert(
&SETTINGS.root_folder,
domain,
SETTINGS.variant,
&cert,
) {
match sequoia_net::wkd::insert(ROOT_FOLDER, domain, SETTINGS.variant, &cert) {
Ok(_) => email,
Err(_) => {
warn!("Unable to create a wkd entry for token {}", token);

View file

@ -1,6 +1,8 @@
use actix_web::http::StatusCode;
use actix_web::{http::StatusCode, HttpResponseBuilder, ResponseError};
use thiserror::Error;
use crate::utils::return_outcome;
#[derive(Error, Debug, Clone, Copy)]
pub enum Error {
#[error("(0x01) Cert is invalid")]
@ -35,7 +37,7 @@ pub enum Error {
MissingFile,
}
impl actix_web::ResponseError for Error {
impl ResponseError for Error {
fn status_code(&self) -> actix_web::http::StatusCode {
match self {
Self::MissingPending => StatusCode::from_u16(404).unwrap(),
@ -45,4 +47,11 @@ impl actix_web::ResponseError for Error {
_ => StatusCode::from_u16(500).unwrap(),
}
}
fn error_response(&self) -> actix_web::HttpResponse<actix_web::body::BoxBody> {
match return_outcome(Err(&self.to_string())) {
Ok(httpbuilder) => httpbuilder,
Err(_) => HttpResponseBuilder::new(self.status_code()).body(self.to_string()),
}
}
}

View file

@ -4,13 +4,13 @@ mod management;
mod settings;
mod utils;
use crate::confirmation::{confirm_action, send_confirmation_email};
use crate::errors::Error;
use crate::settings::SETTINGS;
use crate::utils::is_email_allowed;
use self::confirmation::{confirm_action, send_confirmation_email};
use self::management::{clean_stale, store_pending_addition, store_pending_deletion, Action};
use self::utils::{gen_random_token, get_email_from_cert, parse_pem};
use crate::management::{clean_stale, store_pending_addition, store_pending_deletion, Action};
use crate::settings::{ROOT_FOLDER, SETTINGS};
use crate::utils::{
gen_random_token, get_email_from_cert, is_email_allowed, parse_pem, return_outcome,
};
use actix_files::Files;
use actix_web::http::header::ContentType;
@ -41,21 +41,6 @@ struct Email {
email: String,
}
fn return_success(message: &str) -> Result<HttpResponse, Error> {
let path = webpage_path!().join("success").join("index.html");
let template = match fs::read_to_string(&path) {
Ok(template) => template,
Err(_) => {
debug!("file {} is inaccessible", path.display());
return Err(Error::Inaccessible);
}
};
let page = template.replace("((%m))", message);
return Ok(HttpResponseBuilder::new(StatusCode::OK)
.insert_header(ContentType::html())
.body(page));
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
if let Ok(value) = env::var("RUST_LOG") {
@ -85,11 +70,8 @@ async fn main() -> std::io::Result<()> {
.service(confirm)
.service(delete)
.service(
Files::new(
"/.well-known",
Path::new(&SETTINGS.root_folder).join(".well-known"),
)
.use_hidden_files(),
Files::new("/.well-known", Path::new(&ROOT_FOLDER).join(".well-known"))
.use_hidden_files(),
)
.route("/{filename:.*}", web::get().to(index))
})
@ -133,7 +115,7 @@ async fn submit(pem: web::Form<Key>) -> Result<HttpResponse, Error> {
store_pending_addition(pem.key.clone(), &email, &token)?;
send_confirmation_email(&email, &Action::Add, &token)?;
info!("User {} submitted a key!", &email);
return_success("You submitted your key successfully!")
return_outcome(Ok("You submitted your key successfully!"))
}
#[get("/api/confirm")]
@ -142,11 +124,11 @@ async fn confirm(token: web::Query<Token>) -> Result<HttpResponse, Error> {
match action {
Action::Add => {
info!("Key for user {} was added successfully!", email);
return_success("Your key was added successfully!")
return_outcome(Ok("Your key was added successfully!"))
}
Action::Delete => {
info!("Key for user {} was deleted successfully!", email);
return_success("Your key was deleted successfully!")
return_outcome(Ok("Your key was deleted successfully!"))
}
}
}
@ -157,5 +139,5 @@ async fn delete(email: web::Query<Email>) -> Result<HttpResponse, Error> {
store_pending_deletion(email.email.clone(), &token)?;
send_confirmation_email(&email.email, &Action::Delete, &token)?;
info!("User {} requested the deletion of his key!", email.email);
return_success("You requested the deletion of your key successfully!")
return_outcome(Ok("You requested the deletion of your key successfully!"))
}

View file

@ -1,5 +1,5 @@
use crate::pending_path;
use crate::settings::SETTINGS;
use crate::settings::ROOT_FOLDER;
use crate::utils::{get_user_file_path, key_exists};
use crate::{errors::Error, utils::get_filename};
@ -132,7 +132,7 @@ pub fn clean_stale(max_age: i64) {
}
pub fn delete_key(email: &str) -> Result<(), Error> {
let path = Path::new(&SETTINGS.root_folder).join(get_user_file_path(email)?);
let path = Path::new(&ROOT_FOLDER).join(get_user_file_path(email)?);
match fs::remove_file(path) {
Ok(_) => Ok(()),
Err(_) => Err(Error::Inaccessible),

View file

@ -92,5 +92,6 @@ fn get_mailer() -> SmtpTransport {
mailer
}
pub const ROOT_FOLDER: &str = "data";
pub static SETTINGS: Lazy<Settings> = Lazy::new(get_settings);
pub static MAILER: Lazy<SmtpTransport> = Lazy::new(get_mailer);

View file

@ -1,16 +1,24 @@
use crate::errors::Error;
use crate::settings::SETTINGS;
use crate::{errors::Error, settings::ROOT_FOLDER};
use actix_web::{
http::{header::ContentType, StatusCode},
HttpResponse, HttpResponseBuilder,
};
use flexi_logger::{style, DeferredNow, FileSpec, FlexiLoggerError, Logger, LoggerHandle, Record};
use log::debug;
use rand::{distributions::Alphanumeric, thread_rng, Rng};
use sequoia_net::wkd::Url;
use sequoia_openpgp::{parse::Parse, policy::StandardPolicy, Cert};
use std::path::{Path, PathBuf};
use std::{
fs,
path::{Path, PathBuf},
};
#[macro_export]
macro_rules! pending_path {
() => {
Path::new(&SETTINGS.root_folder).join("pending")
Path::new(&ROOT_FOLDER).join("pending")
};
}
@ -82,7 +90,7 @@ pub fn get_user_file_path(email: &str) -> Result<PathBuf, Error> {
pub fn key_exists(email: &str) -> Result<bool, Error> {
let path = get_user_file_path(email)?;
if !Path::new(&SETTINGS.root_folder).join(path).is_file() {
if !Path::new(&ROOT_FOLDER).join(path).is_file() {
return Err(Error::MissingKey);
}
Ok(true)
@ -135,3 +143,22 @@ pub fn init_logger() -> Result<LoggerHandle, FlexiLoggerError> {
.set_palette("b1;3;2;4;6".to_string())
.start()
}
pub fn return_outcome(data: Result<&str, &str>) -> Result<HttpResponse, Error> {
let path = webpage_path!().join("status").join("index.html");
let template = match fs::read_to_string(&path) {
Ok(template) => template,
Err(_) => {
debug!("file {} is inaccessible", path.display());
return Err(Error::Inaccessible);
}
};
let (page, message) = match data {
Ok(message) => (template.replace("((%s))", "Success!"), message),
Err(message) => (template.replace("((%s))", "Failure!"), message),
};
let page = page.replace("((%m))", message);
return Ok(HttpResponseBuilder::new(StatusCode::OK)
.insert_header(ContentType::html())
.body(page));
}