From 4ebe819106d82459def54561cf8dc71ec22ba6e4 Mon Sep 17 00:00:00 2001 From: metamuffin Date: Tue, 4 Jun 2024 20:48:43 +0200 Subject: save creds --- src/database.rs | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 src/database.rs (limited to 'src/database.rs') 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 { + 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; +} + +impl DatabaseExt for Database { + fn check_or_insert_creds(&self, username: &str, password: &str) -> anyhow::Result { + 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) + } +} -- cgit v1.2.3-70-g09d2