remove extra fields from db, use certificate as storage

This commit is contained in:
yggverse 2024-11-20 08:35:37 +02:00
parent a49ec2b7b4
commit 755a704433
5 changed files with 35 additions and 87 deletions

View File

@ -35,6 +35,9 @@ impl Gemini {
Err(reason) => todo!("{reason}"), Err(reason) => todo!("{reason}"),
}; };
// Get name from subject
let name = certificate.subject_name().unwrap();
// Get expiration time // Get expiration time
let expires = certificate let expires = certificate
.not_valid_after() .not_valid_after()
@ -45,10 +48,7 @@ impl Gemini {
// Append record option // Append record option
widget.form.list.append( widget.form.list.append(
Some(identity.id), Some(identity.id),
&match identity.name { &format!("{name} ({expires})"),
Some(name) => format!("{name} ({expires})"),
None => format!("{expires}"),
},
true, true,
); );
} }
@ -60,6 +60,7 @@ impl Gemini {
widget.on_apply({ widget.on_apply({
let widget = widget.clone(); let widget = widget.clone();
move |response| { move |response| {
// Get record ID depending of user selection
let profile_identity_gemini_id = match response { let profile_identity_gemini_id = match response {
// Use selected identity // Use selected identity
Some(id) => id, Some(id) => id,
@ -78,6 +79,9 @@ impl Gemini {
.auth .auth
.apply(profile_identity_gemini_id, auth_uri.to_string().as_str()) .apply(profile_identity_gemini_id, auth_uri.to_string().as_str())
.unwrap(); //@TODO handle errors .unwrap(); //@TODO handle errors
// Reload page
// @TODO
} }
}); });

View File

@ -6,7 +6,6 @@ use database::Database;
use error::Error; use error::Error;
use gemini::Gemini; use gemini::Gemini;
use gtk::glib::DateTime;
use sqlite::{Connection, Transaction}; use sqlite::{Connection, Transaction};
use std::{rc::Rc, sync::RwLock}; use std::{rc::Rc, sync::RwLock};
@ -27,7 +26,7 @@ impl Identity {
// Get active identity set for profile or create new one // Get active identity set for profile or create new one
let profile_identity_id = Rc::new(match database.active() { let profile_identity_id = Rc::new(match database.active() {
Some(identity) => identity.id, Some(identity) => identity.id,
None => match database.add(profile_id, true, DateTime::now_local().unwrap(), None) { None => match database.add(profile_id, true) {
Ok(id) => id, Ok(id) => id,
Err(_) => return Err(Error::Database), Err(_) => return Err(Error::Database),
}, },

View File

@ -1,4 +1,3 @@
use gtk::glib::DateTime;
use sqlite::{Connection, Error, Transaction}; use sqlite::{Connection, Error, Transaction};
use std::{rc::Rc, sync::RwLock}; use std::{rc::Rc, sync::RwLock};
@ -6,8 +5,6 @@ pub struct Table {
pub id: i64, pub id: i64,
pub profile_id: i64, pub profile_id: i64,
pub is_active: bool, pub is_active: bool,
pub time: DateTime,
pub name: Option<String>,
} }
pub struct Database { pub struct Database {
@ -39,13 +36,7 @@ impl Database {
// Setters // Setters
/// Create new record in `Self` database connected /// Create new record in `Self` database connected
pub fn add( pub fn add(&self, profile_id: Rc<i64>, is_active: bool) -> Result<i64, ()> {
&self,
profile_id: Rc<i64>,
is_active: bool,
time: DateTime,
name: Option<String>,
) -> Result<i64, ()> {
// Begin new transaction // Begin new transaction
let mut writable = self.connection.write().unwrap(); let mut writable = self.connection.write().unwrap();
let tx = writable.transaction().unwrap(); let tx = writable.transaction().unwrap();
@ -54,19 +45,12 @@ impl Database {
if is_active { if is_active {
// Deactivate other records as only one profile should be active // Deactivate other records as only one profile should be active
for record in select(&tx).unwrap() { for record in select(&tx).unwrap() {
let _ = update( let _ = update(&tx, record.profile_id, record.id, false);
&tx,
record.profile_id,
record.id,
false,
record.time,
record.name,
);
} }
} }
// Create new record // Create new record
insert(&tx, profile_id, is_active, time, name).unwrap(); insert(&tx, profile_id, is_active).unwrap();
// Hold insert ID for result // Hold insert ID for result
let id = last_insert_id(&tx); let id = last_insert_id(&tx);
@ -88,8 +72,6 @@ pub fn init(tx: &Transaction) -> Result<usize, Error> {
`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
`profile_id` INTEGER NOT NULL, `profile_id` INTEGER NOT NULL,
`is_active` INTEGER NOT NULL, `is_active` INTEGER NOT NULL,
`time` INTEGER NOT NULL,
`name` VARCHAR(255),
FOREIGN KEY (`profile_id`) REFERENCES `profile`(`id`) FOREIGN KEY (`profile_id`) REFERENCES `profile`(`id`)
)", )",
@ -97,55 +79,34 @@ pub fn init(tx: &Transaction) -> Result<usize, Error> {
) )
} }
pub fn insert( pub fn insert(tx: &Transaction, profile_id: Rc<i64>, is_active: bool) -> Result<usize, Error> {
tx: &Transaction,
profile_id: Rc<i64>,
is_active: bool,
time: DateTime,
name: Option<String>,
) -> Result<usize, Error> {
tx.execute( tx.execute(
"INSERT INTO `profile_identity` ( "INSERT INTO `profile_identity` (
`profile_id`, `profile_id`,
`is_active`, `is_active`
`time`, ) VALUES (?, ?)",
`name` (profile_id, is_active),
) VALUES (?, ?, ?, ?)",
(profile_id, is_active, time.to_unix(), name),
) )
} }
pub fn update( pub fn update(tx: &Transaction, id: i64, profile_id: i64, is_active: bool) -> Result<usize, Error> {
tx: &Transaction,
id: i64,
profile_id: i64,
is_active: bool,
time: DateTime,
name: Option<String>,
) -> Result<usize, Error> {
tx.execute( tx.execute(
"UPDATE `profile_identity` "UPDATE `profile_identity`
SET `profile_id` = ?, SET `profile_id` = ?,
`is_active` = ?, `is_active` = ?
`time` = ?,
`name` = ?
WHERE WHERE
`id` = ?", `id` = ?",
(profile_id, is_active, time.to_unix(), name, id), (profile_id, is_active, id),
) )
} }
pub fn select(tx: &Transaction) -> Result<Vec<Table>, Error> { pub fn select(tx: &Transaction) -> Result<Vec<Table>, Error> {
let mut stmt = tx.prepare( let mut stmt = tx.prepare("SELECT `id`, `profile_id`, `is_active` FROM `profile_identity`")?;
"SELECT `id`, `profile_id`, `is_active`, `time`, `name` FROM `profile_identity`",
)?;
let result = stmt.query_map([], |row| { let result = stmt.query_map([], |row| {
Ok(Table { Ok(Table {
id: row.get(0)?, id: row.get(0)?,
profile_id: row.get(1)?, profile_id: row.get(1)?,
is_active: row.get(2)?, is_active: row.get(2)?,
time: DateTime::from_unix_local(row.get(3)?).unwrap(),
name: row.get(4)?,
}) })
})?; })?;

View File

@ -75,7 +75,7 @@ impl Gemini {
None => "unknown", // @TODO randomize None => "unknown", // @TODO randomize
}, },
) { ) {
Ok(pem) => match self.database.add(&pem, name) { Ok(pem) => match self.database.add(&pem) {
Ok(profile_identity_gemini_id) => { Ok(profile_identity_gemini_id) => {
self.index()?; self.index()?;
Ok(profile_identity_gemini_id) Ok(profile_identity_gemini_id)

View File

@ -1,13 +1,10 @@
use sqlite::{Connection, Error, Transaction}; use sqlite::{Connection, Error, Transaction};
use std::{rc::Rc, sync::RwLock}; use std::{rc::Rc, sync::RwLock};
pub const NAME_MAX_LEN: i32 = 36;
pub struct Table { pub struct Table {
pub id: i64, pub id: i64,
//pub profile_identity_id: i64, //pub profile_identity_id: i64,
pub pem: String, pub pem: String,
pub name: Option<String>,
} }
/// Storage for Gemini auth certificates /// Storage for Gemini auth certificates
@ -30,13 +27,13 @@ impl Database {
// Actions // Actions
/// Create new record in database /// Create new record in database
pub fn add(&self, pem: &str, name: Option<&str>) -> Result<i64, Error> { pub fn add(&self, pem: &str) -> Result<i64, Error> {
// Begin new transaction // Begin new transaction
let mut writable = self.connection.write().unwrap(); // @TODO let mut writable = self.connection.write().unwrap(); // @TODO
let tx = writable.transaction()?; let tx = writable.transaction()?;
// Create new record // Create new record
insert(&tx, *self.profile_identity_id, pem, name)?; insert(&tx, *self.profile_identity_id, pem)?;
// Hold insert ID for result // Hold insert ID for result
let id = last_insert_id(&tx); let id = last_insert_id(&tx);
@ -60,36 +57,25 @@ impl Database {
pub fn init(tx: &Transaction) -> Result<usize, Error> { pub fn init(tx: &Transaction) -> Result<usize, Error> {
tx.execute( tx.execute(
format!( "CREATE TABLE IF NOT EXISTS `profile_identity_gemini`
"CREATE TABLE IF NOT EXISTS `profile_identity_gemini` (
( `id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `profile_identity_id` INTEGER NOT NULL,
`profile_identity_id` INTEGER NOT NULL, `pem` TEXT NOT NULL,
`pem` TEXT NOT NULL,
`name` VARCHAR({}),
FOREIGN KEY (`profile_identity_id`) REFERENCES `profile_identity`(`id`) FOREIGN KEY (`profile_identity_id`) REFERENCES `profile_identity`(`id`)
)", )",
NAME_MAX_LEN
)
.as_str(),
[], [],
) )
} }
pub fn insert( pub fn insert(tx: &Transaction, profile_identity_id: i64, pem: &str) -> Result<usize, Error> {
tx: &Transaction,
profile_identity_id: i64,
pem: &str,
name: Option<&str>,
) -> Result<usize, Error> {
tx.execute( tx.execute(
"INSERT INTO `profile_identity_gemini` ( "INSERT INTO `profile_identity_gemini` (
`profile_identity_id`, `profile_identity_id`,
`pem`, `pem`
`name` ) VALUES (?, ?)",
) VALUES (?, ?, ?)", (profile_identity_id, pem),
(profile_identity_id, pem, name),
) )
} }
@ -97,8 +83,7 @@ pub fn select(tx: &Transaction, profile_identity_id: i64) -> Result<Vec<Table>,
let mut stmt = tx.prepare( let mut stmt = tx.prepare(
"SELECT `id`, "SELECT `id`,
`profile_identity_id`, `profile_identity_id`,
`pem`, `pem`
`name`
FROM `profile_identity_gemini` WHERE `profile_identity_id` = ?", FROM `profile_identity_gemini` WHERE `profile_identity_id` = ?",
)?; )?;
@ -108,7 +93,6 @@ pub fn select(tx: &Transaction, profile_identity_id: i64) -> Result<Vec<Table>,
id: row.get(0)?, id: row.get(0)?,
//profile_identity_id: row.get(1)?, //profile_identity_id: row.get(1)?,
pem: row.get(2)?, pem: row.get(2)?,
name: row.get(3)?,
}) })
})?; })?;