zellij_utils/input/
permission.rs1use std::{
2 collections::HashMap,
3 fs::{self, File},
4 io::Write,
5 path::PathBuf,
6};
7
8use crate::{consts::ZELLIJ_PLUGIN_PERMISSIONS_CACHE, data::PermissionType};
9
10pub type GrantedPermission = HashMap<String, Vec<PermissionType>>;
11
12#[derive(Default, Debug)]
13pub struct PermissionCache {
14 path: PathBuf,
15 granted: GrantedPermission,
16}
17
18impl PermissionCache {
19 pub fn cache(&mut self, plugin_name: String, permissions: Vec<PermissionType>) {
20 self.granted.insert(plugin_name, permissions);
21 }
22
23 pub fn get_permissions(&self, plugin_name: String) -> Option<&Vec<PermissionType>> {
24 self.granted.get(&plugin_name)
25 }
26
27 pub fn check_permissions(
28 &self,
29 plugin_name: String,
30 permissions_to_check: &Vec<PermissionType>,
31 ) -> bool {
32 if let Some(target) = self.granted.get(&plugin_name) {
33 let mut all_granted = true;
34 for permission in permissions_to_check {
35 if !target.contains(permission) {
36 all_granted = false;
37 }
38 }
39 return all_granted;
40 }
41
42 false
43 }
44
45 pub fn from_path_or_default(cache_path: Option<PathBuf>) -> Self {
46 let cache_path = cache_path.unwrap_or(ZELLIJ_PLUGIN_PERMISSIONS_CACHE.to_path_buf());
47
48 let granted = match fs::read_to_string(cache_path.clone()) {
49 Ok(raw_string) => PermissionCache::from_string(raw_string).unwrap_or_default(),
50 Err(e) => {
51 log::error!("Failed to read permission cache file: {}", e);
52 GrantedPermission::default()
53 },
54 };
55
56 PermissionCache {
57 path: cache_path,
58 granted,
59 }
60 }
61
62 pub fn write_to_file(&self) -> std::io::Result<()> {
63 let mut f = File::create(&self.path)?;
64 write!(f, "{}", PermissionCache::to_string(&self.granted))?;
65 Ok(())
66 }
67}