use crate::{
AppState,
models::{oauth_identity, post, user},
};
use ryuk::{
auth,
apikey::api_keys,
oauth_server::{codes, tokens as oauth_tokens},
passkey::passkeys,
push::push_devices,
tokens::one_time_tokens,
};
use ryuk::throttle::Throttle;
use sea_orm::{ColumnTrait, DbErr, EntityTrait, QueryFilter, TransactionTrait};
pub async fn dummy_hash() -> String {
static DUMMY: tokio::sync::OnceCell<String> = tokio::sync::OnceCell::const_new();
DUMMY.get_or_init(|| async { auth::hash_password_async("ryuk-dummy".into()).await.unwrap_or_default() }).await.clone()
}
pub async fn confirm_password(s: &AppState, ip: Option<std::net::IpAddr>, u: &user::Model, given: Option<&str>) -> Result<Result<(), String>, crate::controllers::AppError> {
if !u.has_usable_password {
return Ok(Ok(()));
}
let key = Throttle::key(&format!("account:{}", u.id), ip);
if let Err(locked) = s.throttle.attempt(&key).await {
return Ok(Err(format!("Too many attempts. Try again in {} seconds.", locked.retry_after.as_secs())));
}
let ok = match given {
Some(p) => auth::verify_password_async(p.to_string(), u.password.clone()).await,
None => {
auth::verify_password_async(String::new(), dummy_hash().await).await;
false
}
};
if ok {
s.throttle.clear(&key).await?;
Ok(Ok(()))
} else {
Ok(Err("The password is incorrect.".into()))
}
}
pub async fn sign_out_everywhere(s: &AppState, uid: i64) -> Result<(), crate::controllers::AppError> {
s.oauth.revoke_user_tokens(uid).await?;
s.session_store.delete_for_user(uid).await?;
Ok(())
}
async fn revoke_credentials(s: &AppState, uid: i64) -> Result<(), crate::controllers::AppError> {
s.api_keys.revoke_all(uid).await?;
s.passkeys.delete_all(uid).await?;
sign_out_everywhere(s, uid).await
}
pub async fn delete_user(s: &AppState, uid: i64) -> Result<(), crate::controllers::AppError> {
revoke_credentials(s, uid).await?;
s.db.transaction::<_, (), DbErr>(|tx| {
Box::pin(async move {
post::Entity::delete_many().filter(post::Column::UserId.eq(uid)).exec(tx).await?;
push_devices::Entity::delete_many().filter(push_devices::Column::UserId.eq(uid)).exec(tx).await?;
oauth_identity::Entity::delete_many().filter(oauth_identity::Column::UserId.eq(uid)).exec(tx).await?;
one_time_tokens::Entity::delete_many().filter(one_time_tokens::Column::UserId.eq(uid)).exec(tx).await?;
api_keys::Entity::delete_many().filter(api_keys::Column::OwnerId.eq(uid)).exec(tx).await?;
passkeys::Entity::delete_many().filter(passkeys::Column::OwnerId.eq(uid)).exec(tx).await?;
codes::Entity::delete_many().filter(codes::Column::UserId.eq(uid)).exec(tx).await?;
oauth_tokens::Entity::delete_many().filter(oauth_tokens::Column::UserId.eq(uid)).exec(tx).await?;
user::Entity::delete_by_id(uid).exec(tx).await?;
Ok(())
})
})
.await?;
revoke_credentials(s, uid).await
}