use crate::{ensure_tables, now_unix_secs, random_secret};
use larust_core::AppError;
#[derive(Debug, Clone)]
pub struct NewClient {
pub client_id: String,
pub client_secret: Option<String>,
}
pub async fn create_client(
name: &str,
redirect_uri: &str,
confidential: bool,
) -> Result<NewClient, AppError> {
let pool = larust_orm::pool()?;
ensure_tables(pool).await?;
let client_id = random_secret();
let client_secret = confidential.then(random_secret);
let client_secret_hash = client_secret
.as_deref()
.map(hash_client_secret)
.transpose()?;
let backend = larust_orm::backend();
let insert_sql = format!(
"INSERT INTO oauth_clients (client_id, client_secret_hash, name, redirect_uri, \
is_confidential, created_at) VALUES ({}, {}, {}, {}, {}, {})",
larust_orm::placeholder(backend, 1),
larust_orm::placeholder(backend, 2),
larust_orm::placeholder(backend, 3),
larust_orm::placeholder(backend, 4),
larust_orm::placeholder(backend, 5),
larust_orm::placeholder(backend, 6),
);
sqlx::query(&insert_sql)
.bind(&client_id)
.bind(&client_secret_hash)
.bind(name)
.bind(redirect_uri)
.bind(i64::from(confidential))
.bind(now_unix_secs())
.execute(pool)
.await
.map_err(|source| AppError::Internal(Box::new(source)))?;
Ok(NewClient {
client_id,
client_secret,
})
}
fn hash_client_secret(secret: &str) -> Result<String, AppError> {
larust_auth::hash_password(secret)
}
pub(crate) struct ClientRecord {
pub client_secret_hash: Option<String>,
pub redirect_uri: String,
pub is_confidential: bool,
}
pub(crate) async fn find_client(
pool: &sqlx::AnyPool,
client_id: &str,
) -> Result<Option<ClientRecord>, AppError> {
let select_sql = format!(
"SELECT client_secret_hash, redirect_uri, is_confidential FROM oauth_clients \
WHERE client_id = {}",
larust_orm::placeholder(larust_orm::backend(), 1)
);
let row: Option<(Option<String>, String, i64)> = sqlx::query_as(&select_sql)
.bind(client_id)
.fetch_optional(pool)
.await
.map_err(|source| AppError::Internal(Box::new(source)))?;
Ok(row.map(
|(client_secret_hash, redirect_uri, is_confidential)| ClientRecord {
client_secret_hash,
redirect_uri,
is_confidential: is_confidential != 0,
},
))
}