diff options
Diffstat (limited to 'src/database.rs')
-rw-r--r-- | src/database.rs | 33 |
1 files changed, 33 insertions, 0 deletions
diff --git a/src/database.rs b/src/database.rs new file mode 100644 index 0000000..ac67857 --- /dev/null +++ b/src/database.rs @@ -0,0 +1,33 @@ +use anyhow::Result; +use redb::{Database, ReadableTable, TableDefinition}; +use serde::Deserialize; +use std::path::PathBuf; + +#[derive(Deserialize)] +pub struct Config { + path: PathBuf, +} + +pub fn open_db(config: Config) -> Result<Database> { + let db = Database::create(config.path)?; + + Ok(db) +} + +static T_CREDS: TableDefinition<&str, &str> = TableDefinition::new("creds"); + +pub trait DatabaseExt { + fn check_or_insert_creds(&self, username: &str, password: &str) -> anyhow::Result<bool>; +} + +impl DatabaseExt for Database { + fn check_or_insert_creds(&self, username: &str, password: &str) -> anyhow::Result<bool> { + let txn = self.begin_write()?; + let mut table = txn.open_table(T_CREDS)?; + if let Some(pw) = table.get(username)? { + return Ok(pw.value() == password); + } + table.insert(username, password)?; + Ok(true) + } +} |