pass_manager/src/master_password_check.rs

73 lines
1.9 KiB
Rust
Raw Normal View History

use crate::prelude::*;
use std::sync::Arc;
use teloxide::{
dispatching::{dialogue::GetChatId, DpHandlerDescription},
dptree::Handler,
types::User,
};
pub trait GetUserInfo: GetChatId + Clone + Send + Sync + 'static {
fn user(&self) -> Option<&User>;
}
impl GetUserInfo for Message {
fn user(&self) -> Option<&User> {
self.from()
}
}
impl GetUserInfo for CallbackQuery {
fn user(&self) -> Option<&User> {
Some(&self.from)
}
}
2023-05-09 17:27:58 +00:00
/// A wierd filter that checks for the existance of a master password.
///
/// # Returns
///
/// Returns None if account exists, Some(None) if there's an account and Some(Some(String)) if an error occures.
/// The String represents the error that occured
2023-08-07 10:38:46 +00:00
#[inline]
async fn master_pass_exists<T: GetUserInfo>(
msg: T,
db: DatabaseConnection,
) -> Option<Option<Arc<dyn std::error::Error + Send + Sync>>> {
msg.chat_id()?;
let user_id = match msg.user() {
Some(user) => user.id.0,
None => return Some(Some(Arc::new(NoUserInfo))),
};
match MasterPass::exists(user_id, &db).await {
Ok(true) => None,
Ok(false) => Some(None),
Err(err) => Some(Some(Arc::new(err))),
}
}
2023-08-07 10:38:46 +00:00
#[inline]
async fn notify_about_no_master_pass<T: GetChatId>(
bot: Throttle<Bot>,
result: Option<Arc<dyn std::error::Error + Send + Sync>>,
msg: T,
) -> crate::Result<()> {
if let Some(error) = result {
return Err(error.into());
}
bot.send_message(
msg.chat_id().unwrap(),
"No master password set. Use /set_master_pass to set it",
)
.reply_markup(deletion_markup())
.await?;
Ok(())
}
2023-05-09 17:27:58 +00:00
/// Gets a handler that filters out the messages of users that don't have a master password set
#[inline]
pub fn get_handler<T: GetUserInfo>(
) -> Handler<'static, DependencyMap, crate::Result<()>, DpHandlerDescription> {
dptree::filter_map_async(master_pass_exists::<T>).endpoint(notify_about_no_master_pass::<T>)
}