diff options
Diffstat (limited to 'src/handlers/auth.rs')
-rw-r--r-- | src/handlers/auth.rs | 49 |
1 files changed, 39 insertions, 10 deletions
diff --git a/src/handlers/auth.rs b/src/handlers/auth.rs index cafaeb8..56b38f2 100644 --- a/src/handlers/auth.rs +++ b/src/handlers/auth.rs @@ -1,7 +1,7 @@ use std::{ collections::HashMap, fs::{self, File}, - sync::Arc, + sync::Arc, io::Read, }; use axum::{extract::Query, middleware::Next, response::Response, Extension}; @@ -9,6 +9,7 @@ use axum_macros::debug_handler; use chrono::{Datelike, TimeZone, Utc}; use hyper::Request; use ring::{rand::SystemRandom, signature::Ed25519KeyPair}; +use tracing::debug; use uuid::Uuid; use std::io::Write; @@ -69,24 +70,52 @@ pub async fn requires_auth<B>(req: Request<B>, next: Next<B>) -> Result<Response .and_then(|h| h.to_str().ok()); match auth_header { - Some(h) => Ok(next.run(req).await), + Some(h) => { + debug!("Header: {}", h); + let kp = load_or_gen_keypair()?; + debug!("KP: {:?}", kp); + match paseto::tokens::validate_public_token(h, None, &paseto::tokens::PasetoPublicKey::ED25519KeyPair(&kp), &paseto::tokens::TimeBackend::Chrono) { + Ok(_) => Ok(next.run(req).await), + Err(_) => Err(ServiceError::NotAuthorized) + } + } None => Err(ServiceError::NotAuthorized), } } fn load_or_gen_keypair() -> Result<Ed25519KeyPair, ServiceError> { let kp: Ed25519KeyPair; - if let Ok(c) = fs::read_to_string(".keypair") { - kp = Ed25519KeyPair::from_pkcs8(&hex::decode(c)?)?; - } else { - let srand = SystemRandom::new(); - let pkcs8 = Ed25519KeyPair::generate_pkcs8(&srand)?; - let mut file = match File::open(".keypair") { Ok(f) => f, - Err(_) => File::create(".keypair").unwrap(), + Err(_) => { + debug!("File does not exist, creating at .keypair"); + File::create(".keypair").unwrap() + } }; - file.write(pkcs8.as_ref()); + if let Ok(c) = fs::read(".keypair") { + if c.len() == 0 { + debug!("No keypair found. Generating..."); + + + let srand = SystemRandom::new(); + let pkcs8 = Ed25519KeyPair::generate_pkcs8(&srand)?; + + fs::write(".keypair", pkcs8.as_ref()).unwrap(); + debug!("Written keypair {:?} to .keypair", pkcs8.as_ref()); + + kp = Ed25519KeyPair::from_pkcs8(pkcs8.as_ref())?; + } else { + + debug!("Found keypair file, contents: {:?}", c); + kp = Ed25519KeyPair::from_pkcs8(&c)?; + debug!("Loaded keypair from file"); + } + } else { + debug!("Generating new keypair"); + let srand = SystemRandom::new(); + let pkcs8 = Ed25519KeyPair::generate_pkcs8(&srand)?; + fs::write(".keypair", pkcs8.as_ref()).unwrap(); + debug!("Written keypair {:?} to .keypair", pkcs8.as_ref()); kp = Ed25519KeyPair::from_pkcs8(pkcs8.as_ref())?; } |