mod database;
mod memory;
use anyhow::Result;
use database::Database;
use memory::Memory;
use r2d2::Pool;
use r2d2_sqlite::SqliteConnectionManager;
use sqlite::Transaction;
pub struct Auth {
database: Database,
memory: Memory,
}
impl Auth {
pub fn build(database_pool: &Pool<SqliteConnectionManager>) -> Result<Self> {
let this = Self {
database: Database::build(database_pool),
memory: Memory::new(),
};
Self::index(&this)?;
Ok(this)
}
pub fn apply(&self, profile_identity_id: i64, request: &str) -> Result<i64> {
self.remove(request)?;
let profile_identity_auth_id = self
.database
.add(profile_identity_id, &filter_scope(request))?;
self.index()?;
Ok(profile_identity_auth_id)
}
pub fn remove(&self, request: &str) -> Result<()> {
for record in self.database.records_scope(Some(&filter_scope(request)))? {
self.database.delete(record.id)?;
}
self.index()?;
Ok(())
}
pub fn remove_ref(&self, profile_identity_id: i64) -> Result<()> {
for record in self.database.records_ref(profile_identity_id)? {
self.database.delete(record.id)?;
}
self.index()?;
Ok(())
}
pub fn index(&self) -> Result<()> {
self.memory.clear()?;
for record in self.database.records_scope(None)? {
self.memory.add(record.scope, record.profile_identity_id)?;
}
Ok(())
}
pub fn is_matches(&self, request: &str, profile_identity_id: i64) -> bool {
self.memory
.match_scope(&filter_scope(request))
.is_some_and(|auth| auth.profile_identity_id == profile_identity_id)
}
pub fn total(&self, profile_identity_id: i64) -> usize {
self.memory.total(profile_identity_id)
}
pub fn scope(&self, profile_identity_id: i64) -> Vec<String> {
let mut scope = Vec::new();
match self.database.records_scope(None) {
Ok(result) => {
for auth in result
.iter()
.filter(|this| this.profile_identity_id == profile_identity_id)
{
scope.push(auth.scope.clone())
}
}
Err(_) => todo!(),
}
scope
}
pub fn get(&self, request: &str) -> Option<memory::Auth> {
self.memory.match_scope(&filter_scope(request))
}
}
pub fn migrate(tx: &Transaction) -> Result<()> {
database::init(tx)?;
Ok(())
}
fn filter_scope(url: &str) -> String {
use gtk::glib::{Regex, RegexCompileFlags, RegexMatchFlags};
match Regex::split_simple(
r"^\w+://(.*)",
url,
RegexCompileFlags::DEFAULT,
RegexMatchFlags::DEFAULT,
)
.get(1)
{
Some(postfix) => postfix.to_string(),
None => url.to_string(),
}
.trim()
.trim_end_matches("/")
.to_lowercase()
}