From 2dea604581cafbfbb73443ec2449cda391d12ab7 Mon Sep 17 00:00:00 2001 From: Cara Salter Date: Tue, 28 Jun 2022 07:47:29 -0400 Subject: auth: Initial implementation of auth/begin --- src/handlers/auth.rs | 55 ++++++++++++++++++++++++++++++++++++++++++---------- 1 file changed, 45 insertions(+), 10 deletions(-) (limited to 'src/handlers') diff --git a/src/handlers/auth.rs b/src/handlers/auth.rs index a9ac394..8d65b05 100644 --- a/src/handlers/auth.rs +++ b/src/handlers/auth.rs @@ -1,11 +1,14 @@ -use std::collections::HashMap; +use std::{collections::HashMap, fs::{self, File}}; use axum::{extract::Query, Extension}; use axum_macros::debug_handler; -use pasetors::{claims::Claims, keys::{AsymmetricKeyPair, Generate}, version4::V4}; +use chrono::{Utc, TimeZone, Datelike}; +use ring::{rand::SystemRandom, signature::Ed25519KeyPair}; use uuid::Uuid; -use crate::{errors::{NoneResult, ServiceError}, State}; +use std::io::Write; + +use crate::{errors::{NoneResult, ServiceError, StringResult, TokenResult}, State}; /** @@ -14,21 +17,53 @@ use crate::{errors::{NoneResult, ServiceError}, State}; * for future authentication */ #[debug_handler] -pub async fn begin(Query(params): Query>, Extension(state): Extension) -> NoneResult { +pub async fn begin(Query(params): Query>, Extension(state): Extension) -> TokenResult { if let Some(k) = params.get("key") { if k == &state.gen_key { - let mut claims = Claims::new()?; - claims.non_expiring(); - claims.audience("solard")?; - claims.add_additional("uuid", Uuid::new_v4().to_string())?; + let dt = Utc::now(); + let exp = Utc + .ymd(dt.year() + 1, dt.month(), dt.day()) + .and_hms(0, 0, 0); + let kp = load_or_gen_keypair()?; + + let token = match paseto::tokens::PasetoBuilder::new() + .set_ed25519_key(&kp) + .set_issued_at(Some(dt)) + .set_expiration(&exp) + .set_issuer("solard") + .set_audience("solard") + .set_not_before(&Utc::now()) + .build() { + Ok(token) => token, + Err(_) => { + return Err(ServiceError::Generic(String::from("could not generate paseto key"))); + } + }; - let kp = AsymmetricKeyPair::::generate()?; + return Ok(token.to_string()); + } else { return Err(ServiceError::NotAuthorized); } } else { return Err(ServiceError::Generic("No key supplied".to_string())); } +} + + +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 = File::open(".keypair").unwrap(); + file.write(pkcs8.as_ref()); + + kp = Ed25519KeyPair::from_pkcs8(pkcs8.as_ref())?; + } - Ok(()) + Ok(kp) } -- cgit v1.2.3