use crate::auth::LoginDTO;
use crate::auth::{create_user, find_user_by_username};
use crate::crypto::{CryptoError, Jwks, Jwt, KeyPair};
use rocket::serde::json::Json;
use sqlx::SqlitePool;
use uuid::Uuid;
#[get("/")]
pub fn index() -> &'static str {
"Howdy!"
}
#[get("/.well-known/jwks.json")]
pub fn get_jwks() -> Json<Jwks> {
let mut key_pairs = Vec::<KeyPair>::new();
key_pairs.push(KeyPair::new(&Uuid::new_v4().to_string(), 1_000).unwrap());
key_pairs.push(KeyPair::new(&Uuid::new_v4().to_string(), 10_000).unwrap());
key_pairs.push(KeyPair::new(&Uuid::new_v4().to_string(), 15_000).unwrap());
key_pairs.push(KeyPair::new(&Uuid::new_v4().to_string(), 30_000).unwrap());
Json(Jwks::from_valid_pairs(key_pairs))
}
#[post("/auth?<expired>", data = "<creds>")]
pub async fn auth(
db_pool: &rocket::State<SqlitePool>,
creds: Json<LoginDTO>,
expired: Option<bool>,
) -> Result<String, CryptoError> {
let user_option = find_user_by_username(db_pool, &creds.username)
.await
.map_err(|_| CryptoError::DatabaseError)?;
let user = match user_option {
Some(user) => user,
None => create_user(db_pool, &creds.username, &creds.password)
.await
.map_err(|_| CryptoError::DatabaseError)?,
};
let expiry_time = if expired.unwrap_or(false) {
-36_000
} else {
36_000
};
Ok(Jwt::new(&user.user_id.to_string(), expiry_time)?)
}