ezidam/crates/jwt/src/database.rs

87 lines
2 KiB
Rust

use crate::{Error, PrivateKey, PublicKey};
use chrono::{DateTime, Utc};
use database::sqlx::SqliteExecutor;
use database::Keys as DatabaseKeys;
use id::KeyID;
pub async fn save_new_keys(
conn: impl SqliteExecutor<'_>,
id: &KeyID,
private: &PrivateKey,
public: &PublicKey,
) -> Result<Option<()>, Error> {
Ok(DatabaseKeys::insert(
conn,
&id.0,
private.to_der()?.as_slice(),
public.to_der()?.as_slice(),
)
.await?)
}
pub async fn revoke_all_except_one(
conn: impl SqliteExecutor<'_>,
exception: &KeyID,
) -> Result<Option<()>, Error> {
Ok(DatabaseKeys::revoke_all_except_one(conn, &exception.0).await?)
}
#[derive(Debug)]
pub struct Key {
id: KeyID,
created_at: DateTime<Utc>,
revoked_at: Option<DateTime<Utc>>,
private_der: Vec<u8>,
public_der: Vec<u8>,
}
impl Key {
pub fn key_id(&self) -> &KeyID {
&self.id
}
pub fn created_at(&self) -> DateTime<Utc> {
self.created_at
}
pub fn private_der(&self) -> &[u8] {
&self.private_der
}
pub fn public_der(&self) -> &[u8] {
&self.public_der
}
pub fn is_revoked(&self) -> bool {
self.revoked_at.is_some()
}
}
impl From<DatabaseKeys> for Key {
fn from(db: DatabaseKeys) -> Self {
Self {
id: KeyID(db.id),
created_at: db.created_at,
revoked_at: db.revoked_at,
private_der: db.private_der,
public_der: db.public_der,
}
}
}
impl Key {
pub async fn get_most_recent(conn: impl SqliteExecutor<'_>) -> Result<Option<Self>, Error> {
Ok(DatabaseKeys::get_most_recent(conn).await?.map(Self::from))
}
pub async fn get_all(
conn: impl SqliteExecutor<'_>,
filter_get_revoked: Option<bool>,
) -> Result<Vec<Self>, Error> {
Ok(DatabaseKeys::get_all(conn, filter_get_revoked)
.await?
.into_iter()
.map(Self::from)
.collect::<Vec<_>>())
}
}