continue working on default credentials

This commit is contained in:
2024-06-26 22:24:44 -04:00
parent ce7d75f15a
commit bb980c5eef
5 changed files with 74 additions and 118 deletions

View File

@@ -1,5 +1,3 @@
use std::fmt::Formatter;
use serde::{Serialize, Deserialize};
use sqlx::{
FromRow,
@@ -9,6 +7,7 @@ use sqlx::{
Transaction,
types::Uuid,
};
use tokio_stream::StreamExt;
use crate::errors::*;
@@ -37,7 +36,13 @@ pub trait PersistentCredential: for<'a> Deserialize<'a> + Sized {
type Row: Send + Unpin + for<'r> FromRow<'r, SqliteRow>;
fn type_name() -> &'static str;
fn into_credential(self) -> Credential;
fn row_id(row: &Self::Row) -> Uuid;
fn from_row(row: Self::Row, crypto: &Crypto) -> Result<Self, LoadCredentialsError>;
// save_details needs to be implemented per-type because we don't know the number of parameters in advance
async fn save_details(&self, id: &Uuid, crypto: &Crypto, txn: &mut Transaction<'_, Sqlite>) -> Result<(), SaveCredentialsError>;
@@ -87,9 +92,25 @@ pub trait PersistentCredential: for<'a> Deserialize<'a> + Sized {
Self::from_row(row, crypto)
}
async fn list(pool: &SqlitePool) -> Result<Vec<Self::Row>, LoadCredentialsError> {
let q = format!("SELECT * FROM {}", Self::table_name());
let rows: Vec<Self::Row> = sqlx::query_as(&q).fetch_all(pool).await?;
Ok(rows)
async fn list(crypto: &Crypto, pool: &SqlitePool) -> Result<Vec<(Uuid, Credential)>, LoadCredentialsError> {
let q = format!(
"SELECT details.*
FROM
{} details
JOIN credentials c
ON c.id = details.id
ORDER BY c.created_at",
Self::table_name(),
);
let mut rows = sqlx::query_as::<_, Self::Row>(&q).fetch(pool);
let mut creds = Vec::new();
while let Some(row) = rows.try_next().await? {
let id = Self::row_id(&row);
let cred = Self::from_row(row, crypto)?.into_credential();
creds.push((id, cred));
}
Ok(creds)
}
}