From 57a59a25f623302e674432049e2f2c13d6fea322 Mon Sep 17 00:00:00 2001 From: Cara Salter Date: Tue, 28 Jun 2022 14:10:15 -0400 Subject: auth: Finished PASETO auth Closes #4 --- src/handlers/auth.rs | 49 +++++++++++++++++++++++++++++++++++++++---------- 1 file changed, 39 insertions(+), 10 deletions(-) (limited to 'src/handlers') 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(req: Request, next: Next) -> Result 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 { 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())?; } -- cgit v1.2.3