creddy/src-tauri/src/state.rs

82 lines
2.0 KiB
Rust
Raw Normal View History

2022-11-28 16:16:33 -08:00
use std::collections::HashMap;
use std::sync::RwLock;
use serde::{Serialize, Deserialize};
use tokio::sync::oneshot::Sender;
use crate::ipc;
2022-11-28 16:16:33 -08:00
use crate::errors::*;
#[derive(Serialize, Deserialize)]
2022-11-28 16:16:33 -08:00
#[serde(rename_all = "PascalCase")]
#[serde(untagged)]
pub enum Credentials {
LongLived {
2022-11-28 16:16:33 -08:00
access_key_id: String,
secret_access_key: String,
},
ShortLived {
2022-11-28 16:16:33 -08:00
access_key_id: String,
secret_access_key: String,
token: String,
expiration: String,
},
}
#[derive(Serialize, Deserialize)]
2022-11-28 16:16:33 -08:00
pub enum SessionStatus {
Unlocked,
Locked,
Empty,
}
pub struct AppState {
2022-11-28 16:16:33 -08:00
status: RwLock<SessionStatus>,
credentials: RwLock<Option<Credentials>>,
request_count: RwLock<u64>,
2022-11-28 16:16:33 -08:00
open_requests: RwLock<HashMap<u64, Sender<ipc::Approval>>>,
}
impl AppState {
2022-11-28 16:16:33 -08:00
pub fn new(status: SessionStatus, creds: Option<Credentials>) -> Self {
AppState {
2022-11-28 16:16:33 -08:00
status: RwLock::new(status),
credentials: RwLock::new(creds),
request_count: RwLock::new(0),
open_requests: RwLock::new(HashMap::new()),
}
}
2022-11-28 16:16:33 -08:00
pub fn register_request(&self, chan: Sender<ipc::Approval>) -> u64 {
let count = {
let c = self.request_count.write().unwrap();
*c += 1;
c
};
let open_requests = self.open_requests.write().unwrap();
2022-11-28 16:16:33 -08:00
open_requests.insert(*count, chan);
*count
}
2022-11-28 16:16:33 -08:00
pub fn send_response(&self, response: ipc::RequestResponse) -> Result<(), SendResponseError> {
let mut open_requests = self.open_requests.write().unwrap();
2022-11-28 16:16:33 -08:00
let chan = open_requests
.remove(&response.id)
.ok_or(SendResponseError::NotFound)
?;
2022-11-28 16:16:33 -08:00
chan.send(response.approval)
.map_err(|_e| SendResponseError::Abandoned)
}
2022-11-28 16:16:33 -08:00
pub fn get_creds_serialized(&self) -> String {
let creds = self.credentials.read().unwrap();
// fix this at some point
serde_json::to_string(&creds.unwrap()).unwrap()
}
}