make multi-protocol identity feature

This commit is contained in:
yggverse 2025-01-23 10:57:12 +02:00
parent 92550a2ccc
commit 12d79792d9
33 changed files with 309 additions and 593 deletions

View file

@ -1,51 +1,144 @@
mod auth;
mod certificate;
mod database;
mod error;
mod gemini;
mod item;
mod memory;
use auth::Auth;
use database::Database;
pub use error::Error;
use gemini::Gemini;
use item::Item;
use memory::Memory;
use gtk::glib::DateTime;
use sqlite::{Connection, Transaction};
use std::{rc::Rc, sync::RwLock};
/// Authorization wrapper for different protocols
/// Authorization wrapper for Gemini protocol
///
/// https://geminiprotocol.net/docs/protocol-specification.gmi#client-certificates
pub struct Identity {
// database: Rc<Database>,
pub gemini: Rc<Gemini>,
pub auth: Rc<Auth>,
pub database: Rc<Database>,
pub memory: Rc<Memory>,
}
impl Identity {
// Constructors
/// Create new `Self`
pub fn build(connection: &Rc<RwLock<Connection>>, profile_id: &Rc<i64>) -> Result<Self, Error> {
// Init identity database
let database = Rc::new(Database::build(connection));
pub fn build(
connection: &Rc<RwLock<Connection>>,
profile_identity_id: &Rc<i64>,
) -> Result<Self, Error> {
// Init components
let auth = match Auth::new(connection) {
Ok(auth) => Rc::new(auth),
Err(e) => return Err(Error::Auth(e)),
};
let database = Rc::new(Database::build(connection, profile_identity_id));
let memory = Rc::new(Memory::new());
// Get active identity set for profile or create new one
let profile_identity_id = Rc::new(match database.active() {
Ok(result) => match result {
Some(identity) => identity.id,
None => match database.add(profile_id, true) {
Ok(id) => id,
Err(e) => return Err(Error::Database(e)),
},
// Init `Self`
let this = Self {
auth,
database,
memory,
};
// Build initial index
Self::index(&this)?;
Ok(this)
}
// Actions
/// Add new record to database, update memory index
/// * return new `profile_identity_id` on success
pub fn add(&self, pem: &str) -> Result<i64, Error> {
match self.database.add(pem) {
Ok(profile_identity_id) => {
self.index()?;
Ok(profile_identity_id)
}
Err(e) => Err(Error::Database(e)),
}
}
/// Delete record from database including children dependencies, update memory index
pub fn delete(&self, profile_identity_id: i64) -> Result<(), Error> {
match self.auth.remove_ref(profile_identity_id) {
Ok(_) => match self.database.delete(profile_identity_id) {
Ok(_) => {
self.index()?;
Ok(())
}
Err(e) => Err(Error::Database(e)),
},
Err(e) => Err(Error::Auth(e)),
}
}
/// Generate new certificate and insert record to DB, update memory index
/// * return new `profile_identity_id` on success
pub fn make(&self, time: Option<(DateTime, DateTime)>, name: &str) -> Result<i64, Error> {
// Generate new certificate
match certificate::generate(
match time {
Some(value) => value,
None => (
DateTime::now_local().unwrap(),
DateTime::from_local(9999, 12, 31, 23, 59, 59.9).unwrap(), // max @TODO
),
},
name,
) {
Ok(pem) => self.add(&pem),
Err(e) => Err(Error::Certificate(e)),
}
}
/// Create new `Memory` index from `Database` for `Self`
pub fn index(&self) -> Result<(), Error> {
// Clear previous records
if let Err(e) = self.memory.clear() {
return Err(Error::Memory(e));
}
// Build new index
match self.database.records() {
Ok(records) => {
for record in records {
if let Err(e) = self.memory.add(record.id, record.pem) {
return Err(Error::Memory(e));
}
}
}
Err(e) => return Err(Error::Database(e)),
});
};
// Init gemini component
let gemini = Rc::new(match Gemini::build(connection, &profile_identity_id) {
Ok(result) => result,
Err(e) => return Err(Error::Gemini(e)),
});
Ok(())
}
// Done
Ok(Self {
// database,
gemini,
})
/// Get `Identity` match `request`
/// * [Client certificates specification](https://geminiprotocol.net/docs/protocol-specification.gmi#client-certificates)
/// * this function work with memory cache (not database)
pub fn match_scope(&self, request: &str) -> Option<Item> {
if let Some(auth) = self.auth.memory.match_scope(request) {
match self.memory.get(auth.profile_identity_id) {
Ok(pem) => {
return Some(Item {
// scope: auth.scope,
pem,
});
}
Err(e) => todo!("{:?}", e.to_string()),
}
}
None
}
}
@ -58,7 +151,7 @@ pub fn migrate(tx: &Transaction) -> Result<(), String> {
}
// Delegate migration to childs
gemini::migrate(tx)?;
auth::migrate(tx)?;
// Success
Ok(())

View file

@ -11,7 +11,7 @@ use memory::Memory;
use sqlite::{Connection, Transaction};
use std::{rc::Rc, sync::RwLock};
/// API for `profile_identity_gemini_id` + `scope` auth pairs operations
/// API for `profile_identity_id` + `scope` auth pairs operations
pub struct Auth {
pub database: Rc<Database>,
pub memory: Rc<Memory>,
@ -37,26 +37,25 @@ impl Auth {
// Actions
/// Apply `profile_identity_gemini_id` certificate as the auth for `scope`
/// Apply `profile_identity_id` certificate as the auth for `scope`
/// * deactivate active auth by remove previous records from `Self` database
/// * reindex `Self` memory index on success
/// * return last insert `profile_identity_gemini_auth_id` on success
pub fn apply(&self, profile_identity_gemini_id: i64, scope: &str) -> Result<i64, Error> {
/// * return last insert `profile_identity_auth_id` on success
pub fn apply(&self, profile_identity_id: i64, scope: &str) -> Result<i64, Error> {
// Cleanup records match `scope` (unauthorize)
self.remove_scope(scope)?;
// Create new record (auth)
let profile_identity_gemini_auth_id =
match self.database.add(profile_identity_gemini_id, scope) {
Ok(id) => id,
Err(e) => return Err(Error::Database(e)),
};
let profile_identity_auth_id = match self.database.add(profile_identity_id, scope) {
Ok(id) => id,
Err(e) => return Err(Error::Database(e)),
};
// Reindex
self.index()?;
// Done
Ok(profile_identity_gemini_auth_id)
Ok(profile_identity_auth_id)
}
/// Remove all records match request (unauthorize)
@ -75,9 +74,9 @@ impl Auth {
Ok(())
}
/// Remove all records match `profile_identity_gemini_id` foreign reference key
pub fn remove_ref(&self, profile_identity_gemini_id: i64) -> Result<(), Error> {
match self.database.records_ref(profile_identity_gemini_id) {
/// Remove all records match `profile_identity_id` foreign reference key
pub fn remove_ref(&self, profile_identity_id: i64) -> Result<(), Error> {
match self.database.records_ref(profile_identity_id) {
Ok(records) => {
for record in records {
if let Err(e) = self.database.delete(record.id) {
@ -102,10 +101,7 @@ impl Auth {
match self.database.records_scope(None) {
Ok(records) => {
for record in records {
if let Err(e) = self
.memory
.add(record.scope, record.profile_identity_gemini_id)
{
if let Err(e) = self.memory.add(record.scope, record.profile_identity_id) {
return Err(Error::Memory(e));
}
}

View file

@ -3,11 +3,11 @@ use std::{rc::Rc, sync::RwLock};
pub struct Table {
pub id: i64,
pub profile_identity_gemini_id: i64,
pub profile_identity_id: i64,
pub scope: String,
}
/// Storage for `profile_identity_gemini_id` + `scope` auth pairs
/// Storage for `profile_identity_id` + `scope` auth pairs
pub struct Database {
connection: Rc<RwLock<Connection>>,
}
@ -25,13 +25,13 @@ impl Database {
// Actions
/// Create new record in database
pub fn add(&self, profile_identity_gemini_id: i64, scope: &str) -> Result<i64, Error> {
pub fn add(&self, profile_identity_id: i64, scope: &str) -> Result<i64, Error> {
// Begin new transaction
let mut writable = self.connection.write().unwrap(); // @TODO
let tx = writable.transaction()?;
// Create new record
insert(&tx, profile_identity_gemini_id, scope)?;
insert(&tx, profile_identity_id, scope)?;
// Hold insert ID for result
let id = last_insert_id(&tx);
@ -69,10 +69,10 @@ impl Database {
}
/// Get records from database match current `profile_id` optionally filtered by `scope`
pub fn records_ref(&self, profile_identity_gemini_id: i64) -> Result<Vec<Table>, Error> {
pub fn records_ref(&self, profile_identity_id: i64) -> Result<Vec<Table>, Error> {
let readable = self.connection.read().unwrap(); // @TODO
let tx = readable.unchecked_transaction()?;
select_ref(&tx, profile_identity_gemini_id)
select_ref(&tx, profile_identity_id)
}
}
@ -80,54 +80,47 @@ impl Database {
pub fn init(tx: &Transaction) -> Result<usize, Error> {
tx.execute(
"CREATE TABLE IF NOT EXISTS `profile_identity_gemini_auth`
"CREATE TABLE IF NOT EXISTS `profile_identity_auth`
(
`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
`profile_identity_gemini_id` INTEGER NOT NULL,
`scope` VARCHAR(1024) NOT NULL,
`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
`profile_identity_id` INTEGER NOT NULL,
`scope` VARCHAR(1024) NOT NULL,
FOREIGN KEY (`profile_identity_gemini_id`) REFERENCES `profile_identity_gemini`(`id`),
FOREIGN KEY (`profile_identity_id`) REFERENCES `profile_identity`(`id`),
UNIQUE (`scope`)
)",
[],
)
}
pub fn insert(
tx: &Transaction,
profile_identity_gemini_id: i64,
scope: &str,
) -> Result<usize, Error> {
pub fn insert(tx: &Transaction, profile_identity_id: i64, scope: &str) -> Result<usize, Error> {
tx.execute(
"INSERT INTO `profile_identity_gemini_auth` (
`profile_identity_gemini_id`,
"INSERT INTO `profile_identity_auth` (
`profile_identity_id`,
`scope`
) VALUES (?, ?)",
(profile_identity_gemini_id, scope),
(profile_identity_id, scope),
)
}
pub fn delete(tx: &Transaction, id: i64) -> Result<usize, Error> {
tx.execute(
"DELETE FROM `profile_identity_gemini_auth` WHERE `id` = ?",
[id],
)
tx.execute("DELETE FROM `profile_identity_auth` WHERE `id` = ?", [id])
}
pub fn select_scope(tx: &Transaction, scope: Option<&str>) -> Result<Vec<Table>, Error> {
let mut stmt = tx.prepare(
"SELECT `id`,
`profile_identity_gemini_id`,
`profile_identity_id`,
`scope`
FROM `profile_identity_gemini_auth`
FROM `profile_identity_auth`
WHERE `scope` LIKE ?",
)?;
let result = stmt.query_map([scope.unwrap_or("%")], |row| {
Ok(Table {
id: row.get(0)?,
profile_identity_gemini_id: row.get(1)?,
profile_identity_id: row.get(1)?,
scope: row.get(2)?,
})
})?;
@ -142,20 +135,20 @@ pub fn select_scope(tx: &Transaction, scope: Option<&str>) -> Result<Vec<Table>,
Ok(records)
}
pub fn select_ref(tx: &Transaction, profile_identity_gemini_id: i64) -> Result<Vec<Table>, Error> {
pub fn select_ref(tx: &Transaction, profile_identity_id: i64) -> Result<Vec<Table>, Error> {
let mut stmt = tx.prepare(
"SELECT `id`,
`profile_identity_gemini_id`,
`profile_identity_id`,
`scope`
FROM `profile_identity_gemini_auth`
WHERE `profile_identity_gemini_id` = ?",
FROM `profile_identity_auth`
WHERE `profile_identity_id` = ?",
)?;
let result = stmt.query_map([profile_identity_gemini_id], |row| {
let result = stmt.query_map([profile_identity_id], |row| {
Ok(Table {
id: row.get(0)?,
profile_identity_gemini_id: row.get(1)?,
profile_identity_id: row.get(1)?,
scope: row.get(2)?,
})
})?;

View file

@ -29,9 +29,9 @@ impl Memory {
// Actions
/// Add new record with `scope` as key and `profile_identity_gemini_id` as value
/// Add new record with `scope` as key and `profile_identity_id` as value
/// * validate record with same key does not exist yet
pub fn add(&self, scope: String, profile_identity_gemini_id: i64) -> Result<(), Error> {
pub fn add(&self, scope: String, profile_identity_id: i64) -> Result<(), Error> {
// Borrow shared index access
let mut index = self.index.borrow_mut();
@ -41,7 +41,7 @@ impl Memory {
}
// Slot should be free, let check it twice
match index.insert(scope, profile_identity_gemini_id) {
match index.insert(scope, profile_identity_id) {
Some(_) => Err(Error::Unexpected),
None => Ok(()),
}
@ -65,10 +65,10 @@ impl Memory {
let mut result = Vec::new();
// Get all records starts with `scope`
for (scope, &profile_identity_gemini_id) in self.index.borrow().iter() {
if alias(request).starts_with(scope) {
for (scope, &profile_identity_id) in self.index.borrow().iter() {
if request.starts_with(scope) {
result.push(Auth {
profile_identity_gemini_id,
profile_identity_id,
scope: scope.clone(),
})
}
@ -81,12 +81,3 @@ impl Memory {
result.first().cloned()
}
}
// Tools
// @TODO optional
fn alias(request: &str) -> String {
request
.replace("gemini://", "titan://")
.replace("titan://", "gemini://")
}

View file

@ -1,5 +1,5 @@
#[derive(Clone)]
pub struct Auth {
pub profile_identity_gemini_id: i64,
pub profile_identity_id: i64,
pub scope: String,
}

View file

@ -3,57 +3,37 @@ use std::{rc::Rc, sync::RwLock};
pub struct Table {
pub id: i64,
pub profile_id: i64,
pub is_active: bool,
//pub profile_id: i64,
pub pem: String,
}
/// Storage for Gemini auth certificates
pub struct Database {
pub connection: Rc<RwLock<Connection>>,
connection: Rc<RwLock<Connection>>,
profile_id: Rc<i64>, // multi-profile relationship
}
impl Database {
// Constructors
/// Create new `Self`
pub fn build(connection: &Rc<RwLock<Connection>>) -> Self {
pub fn build(connection: &Rc<RwLock<Connection>>, profile_id: &Rc<i64>) -> Self {
Self {
connection: connection.clone(),
profile_id: profile_id.clone(),
}
}
// Getters
// Actions
/// Get all records
pub fn records(&self) -> Result<Vec<Table>, Error> {
let readable = self.connection.read().unwrap();
let tx = readable.unchecked_transaction()?;
select(&tx)
}
/// Get active identity record if exist
pub fn active(&self) -> Result<Option<Table>, Error> {
let records = self.records()?;
Ok(records.into_iter().find(|record| record.is_active))
}
// Setters
/// Create new record in `Self` database connected
pub fn add(&self, profile_id: &Rc<i64>, is_active: bool) -> Result<i64, Error> {
/// Create new record in database
pub fn add(&self, pem: &str) -> Result<i64, Error> {
// Begin new transaction
let mut writable = self.connection.write().unwrap();
let mut writable = self.connection.write().unwrap(); // @TODO
let tx = writable.transaction()?;
// New record has active status
if is_active {
// Deactivate other records as only one profile should be active
for record in select(&tx)? {
update(&tx, record.profile_id, record.id, false)?;
}
}
// Create new record
insert(&tx, profile_id, is_active)?;
insert(&tx, *self.profile_id, pem)?;
// Hold insert ID for result
let id = last_insert_id(&tx);
@ -64,6 +44,44 @@ impl Database {
Err(e) => Err(e),
}
}
/// Delete record with given `id` from database
pub fn delete(&self, id: i64) -> Result<(), Error> {
// Begin new transaction
let mut writable = self.connection.write().unwrap(); // @TODO
let tx = writable.transaction()?;
// Create new record
delete(&tx, id)?;
// Done
match tx.commit() {
Ok(_) => Ok(()),
Err(e) => Err(e),
}
}
/// Get single record match `id`
pub fn record(&self, id: i64) -> Result<Option<Table>, Error> {
let readable = self.connection.read().unwrap();
let tx = readable.unchecked_transaction()?;
let records = select(&tx, *self.profile_id)?; // @TODO single record query
for record in records {
if record.id == id {
return Ok(Some(record));
}
}
Ok(None)
}
/// Get all records match current `profile_id`
pub fn records(&self) -> Result<Vec<Table>, Error> {
let readable = self.connection.read().unwrap(); // @TODO
let tx = readable.unchecked_transaction()?;
select(&tx, *self.profile_id)
}
}
// Low-level DB API
@ -74,7 +92,7 @@ pub fn init(tx: &Transaction) -> Result<usize, Error> {
(
`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
`profile_id` INTEGER NOT NULL,
`is_active` INTEGER NOT NULL,
`pem` TEXT NOT NULL,
FOREIGN KEY (`profile_id`) REFERENCES `profile`(`id`)
)",
@ -82,34 +100,34 @@ pub fn init(tx: &Transaction) -> Result<usize, Error> {
)
}
pub fn insert(tx: &Transaction, profile_id: &Rc<i64>, is_active: bool) -> Result<usize, Error> {
pub fn insert(tx: &Transaction, profile_id: i64, pem: &str) -> Result<usize, Error> {
tx.execute(
"INSERT INTO `profile_identity` (
`profile_id`,
`is_active`
`pem`
) VALUES (?, ?)",
(profile_id, is_active),
(profile_id, pem),
)
}
pub fn update(tx: &Transaction, id: i64, profile_id: i64, is_active: bool) -> Result<usize, Error> {
tx.execute(
"UPDATE `profile_identity`
SET `profile_id` = ?,
`is_active` = ?
WHERE
`id` = ?",
(profile_id, is_active, id),
)
pub fn delete(tx: &Transaction, id: i64) -> Result<usize, Error> {
tx.execute("DELETE FROM `profile_identity` WHERE `id` = ?", [id])
}
pub fn select(tx: &Transaction) -> Result<Vec<Table>, Error> {
let mut stmt = tx.prepare("SELECT `id`, `profile_id`, `is_active` FROM `profile_identity`")?;
let result = stmt.query_map([], |row| {
pub fn select(tx: &Transaction, profile_id: i64) -> Result<Vec<Table>, Error> {
let mut stmt = tx.prepare(
"SELECT `id`,
`profile_id`,
`pem`
FROM `profile_identity` WHERE `profile_id` = ?",
)?;
let result = stmt.query_map([profile_id], |row| {
Ok(Table {
id: row.get(0)?,
profile_id: row.get(1)?,
is_active: row.get(2)?,
//profile_id: row.get(1)?,
pem: row.get(2)?,
})
})?;

View file

@ -2,19 +2,23 @@ use std::fmt::{Display, Formatter, Result};
#[derive(Debug)]
pub enum Error {
Auth(super::auth::Error),
Certificate(Box<dyn std::error::Error>),
Database(sqlite::Error),
Gemini(super::gemini::Error),
Memory(super::memory::Error),
}
impl Display for Error {
fn fmt(&self, f: &mut Formatter) -> Result {
match self {
Self::Auth(e) => write!(f, "Could not create auth: {e}"),
Self::Certificate(e) => {
write!(f, "Could not create certificate: {e}")
}
Self::Database(e) => {
write!(f, "Database error: {e}")
}
Self::Gemini(e) => {
write!(f, "Could not init Gemini identity: {e}")
}
Self::Memory(e) => write!(f, "Memory error: {e}"),
}
}
}

View file

@ -1,158 +0,0 @@
mod auth;
mod certificate;
mod database;
mod error;
mod identity;
mod memory;
use auth::Auth;
use database::Database;
pub use error::Error;
use identity::Identity;
use memory::Memory;
use gtk::glib::DateTime;
use sqlite::{Connection, Transaction};
use std::{rc::Rc, sync::RwLock};
/// Authorization wrapper for Gemini protocol
///
/// https://geminiprotocol.net/docs/protocol-specification.gmi#client-certificates
pub struct Gemini {
pub auth: Rc<Auth>,
pub database: Rc<Database>,
pub memory: Rc<Memory>,
}
impl Gemini {
// Constructors
/// Create new `Self`
pub fn build(
connection: &Rc<RwLock<Connection>>,
profile_identity_id: &Rc<i64>,
) -> Result<Self, Error> {
// Init components
let auth = match Auth::new(connection) {
Ok(auth) => Rc::new(auth),
Err(e) => return Err(Error::Auth(e)),
};
let database = Rc::new(Database::build(connection, profile_identity_id));
let memory = Rc::new(Memory::new());
// Init `Self`
let this = Self {
auth,
database,
memory,
};
// Build initial index
Self::index(&this)?;
Ok(this)
}
// Actions
/// Add new record to database, update memory index
/// * return new `profile_identity_gemini_id` on success
pub fn add(&self, pem: &str) -> Result<i64, Error> {
match self.database.add(pem) {
Ok(profile_identity_gemini_id) => {
self.index()?;
Ok(profile_identity_gemini_id)
}
Err(e) => Err(Error::Database(e)),
}
}
/// Delete record from database including children dependencies, update memory index
pub fn delete(&self, profile_identity_gemini_id: i64) -> Result<(), Error> {
match self.auth.remove_ref(profile_identity_gemini_id) {
Ok(_) => match self.database.delete(profile_identity_gemini_id) {
Ok(_) => {
self.index()?;
Ok(())
}
Err(e) => Err(Error::Database(e)),
},
Err(e) => Err(Error::Auth(e)),
}
}
/// Generate new certificate and insert record to DB, update memory index
/// * return new `profile_identity_gemini_id` on success
pub fn make(&self, time: Option<(DateTime, DateTime)>, name: &str) -> Result<i64, Error> {
// Generate new certificate
match certificate::generate(
match time {
Some(value) => value,
None => (
DateTime::now_local().unwrap(),
DateTime::from_local(9999, 12, 31, 23, 59, 59.9).unwrap(), // max @TODO
),
},
name,
) {
Ok(pem) => self.add(&pem),
Err(e) => Err(Error::Certificate(e)),
}
}
/// Create new `Memory` index from `Database` for `Self`
pub fn index(&self) -> Result<(), Error> {
// Clear previous records
if let Err(e) = self.memory.clear() {
return Err(Error::Memory(e));
}
// Build new index
match self.database.records() {
Ok(records) => {
for record in records {
if let Err(e) = self.memory.add(record.id, record.pem) {
return Err(Error::Memory(e));
}
}
}
Err(e) => return Err(Error::Database(e)),
};
Ok(())
}
/// Get `Identity` match `request`
/// * [Client certificates specification](https://geminiprotocol.net/docs/protocol-specification.gmi#client-certificates)
/// * this function work with memory cache (not database)
pub fn match_scope(&self, request: &str) -> Option<Identity> {
if let Some(auth) = self.auth.memory.match_scope(request) {
match self.memory.get(auth.profile_identity_gemini_id) {
Ok(pem) => {
return Some(Identity {
// scope: auth.scope,
pem,
});
}
Err(e) => todo!("{:?}", e.to_string()),
}
}
None
}
}
// Tools
pub fn migrate(tx: &Transaction) -> Result<(), String> {
// Migrate self components
if let Err(e) = database::init(tx) {
return Err(e.to_string());
}
// Delegate migration to childs
auth::migrate(tx)?;
// Success
Ok(())
}

View file

@ -1,146 +0,0 @@
use sqlite::{Connection, Error, Transaction};
use std::{rc::Rc, sync::RwLock};
pub struct Table {
pub id: i64,
//pub profile_identity_id: i64,
pub pem: String,
}
/// Storage for Gemini auth certificates
pub struct Database {
connection: Rc<RwLock<Connection>>,
profile_identity_id: Rc<i64>, // multi-profile relationship
}
impl Database {
// Constructors
/// Create new `Self`
pub fn build(connection: &Rc<RwLock<Connection>>, profile_identity_id: &Rc<i64>) -> Self {
Self {
connection: connection.clone(),
profile_identity_id: profile_identity_id.clone(),
}
}
// Actions
/// Create new record in database
pub fn add(&self, pem: &str) -> Result<i64, Error> {
// Begin new transaction
let mut writable = self.connection.write().unwrap(); // @TODO
let tx = writable.transaction()?;
// Create new record
insert(&tx, *self.profile_identity_id, pem)?;
// Hold insert ID for result
let id = last_insert_id(&tx);
// Done
match tx.commit() {
Ok(_) => Ok(id),
Err(e) => Err(e),
}
}
/// Delete record with given `id` from database
pub fn delete(&self, id: i64) -> Result<(), Error> {
// Begin new transaction
let mut writable = self.connection.write().unwrap(); // @TODO
let tx = writable.transaction()?;
// Create new record
delete(&tx, id)?;
// Done
match tx.commit() {
Ok(_) => Ok(()),
Err(e) => Err(e),
}
}
/// Get single record match `id`
pub fn record(&self, id: i64) -> Result<Option<Table>, Error> {
let readable = self.connection.read().unwrap();
let tx = readable.unchecked_transaction()?;
let records = select(&tx, *self.profile_identity_id)?; // @TODO single record query
for record in records {
if record.id == id {
return Ok(Some(record));
}
}
Ok(None)
}
/// Get all records match current `profile_identity_id`
pub fn records(&self) -> Result<Vec<Table>, Error> {
let readable = self.connection.read().unwrap(); // @TODO
let tx = readable.unchecked_transaction()?;
select(&tx, *self.profile_identity_id)
}
}
// Low-level DB API
pub fn init(tx: &Transaction) -> Result<usize, Error> {
tx.execute(
"CREATE TABLE IF NOT EXISTS `profile_identity_gemini`
(
`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
`profile_identity_id` INTEGER NOT NULL,
`pem` TEXT NOT NULL,
FOREIGN KEY (`profile_identity_id`) REFERENCES `profile_identity`(`id`)
)",
[],
)
}
pub fn insert(tx: &Transaction, profile_identity_id: i64, pem: &str) -> Result<usize, Error> {
tx.execute(
"INSERT INTO `profile_identity_gemini` (
`profile_identity_id`,
`pem`
) VALUES (?, ?)",
(profile_identity_id, pem),
)
}
pub fn delete(tx: &Transaction, id: i64) -> Result<usize, Error> {
tx.execute("DELETE FROM `profile_identity_gemini` WHERE `id` = ?", [id])
}
pub fn select(tx: &Transaction, profile_identity_id: i64) -> Result<Vec<Table>, Error> {
let mut stmt = tx.prepare(
"SELECT `id`,
`profile_identity_id`,
`pem`
FROM `profile_identity_gemini` WHERE `profile_identity_id` = ?",
)?;
let result = stmt.query_map([profile_identity_id], |row| {
Ok(Table {
id: row.get(0)?,
//profile_identity_id: row.get(1)?,
pem: row.get(2)?,
})
})?;
let mut records = Vec::new();
for record in result {
let table = record?;
records.push(table);
}
Ok(records)
}
pub fn last_insert_id(tx: &Transaction) -> i64 {
tx.last_insert_rowid()
}

View file

@ -1,24 +0,0 @@
use std::fmt::{Display, Formatter, Result};
#[derive(Debug)]
pub enum Error {
Auth(super::auth::Error),
Certificate(Box<dyn std::error::Error>),
Database(sqlite::Error),
Memory(super::memory::Error),
}
impl Display for Error {
fn fmt(&self, f: &mut Formatter) -> Result {
match self {
Self::Auth(e) => write!(f, "Could not create auth: {e}"),
Self::Certificate(e) => {
write!(f, "Could not create certificate: {e}")
}
Self::Database(e) => {
write!(f, "Database error: {e}")
}
Self::Memory(e) => write!(f, "Memory error: {e}"),
}
}
}

View file

@ -5,12 +5,12 @@ use gtk::gio::TlsCertificate;
/// Gemini identity holder for cached record in application-wide struct format.
/// Implements also additional conversion methods.
pub struct Identity {
pub struct Item {
pub pem: String,
// pub scope: String,
}
impl Identity {
impl Item {
/// Convert `Self` to [TlsCertificate](https://docs.gtk.org/gio/class.TlsCertificate.html)
pub fn to_tls_certificate(&self) -> Result<TlsCertificate, Error> {
match TlsCertificate::from_pem(&self.pem) {

View file

@ -28,17 +28,17 @@ impl Memory {
/// Add new record with `id` as key and `pem` as value
/// * validate record with same key does not exist yet
pub fn add(&self, profile_identity_gemini_id: i64, pem: String) -> Result<(), Error> {
pub fn add(&self, profile_identity_id: i64, pem: String) -> Result<(), Error> {
// Borrow shared index access
let mut index = self.index.borrow_mut();
// Prevent existing key overwrite
if index.contains_key(&profile_identity_gemini_id) {
return Err(Error::Overwrite(profile_identity_gemini_id));
if index.contains_key(&profile_identity_id) {
return Err(Error::Overwrite(profile_identity_id));
}
// Slot should be free, let check it twice
match index.insert(profile_identity_gemini_id, pem) {
match index.insert(profile_identity_id, pem) {
Some(_) => Err(Error::Unexpected),
None => Ok(()),
}