|
|
@@ -1,5 +1,8 @@
|
|
|
use uuid::Uuid;
|
|
|
+use serde::{Serialize, Deserialize};
|
|
|
+use std::{fs, io::Write, path::Path};
|
|
|
|
|
|
+#[derive(Debug, Serialize, Deserialize)]
|
|
|
pub struct User {
|
|
|
pub id: Uuid,
|
|
|
pub name: String,
|
|
|
@@ -8,12 +11,53 @@ pub struct User {
|
|
|
pub devices: Vec<Device>
|
|
|
}
|
|
|
|
|
|
+#[derive(Debug, Serialize, Deserialize)]
|
|
|
pub struct Device {
|
|
|
id: String,
|
|
|
device_type: DeviceType,
|
|
|
name: String
|
|
|
}
|
|
|
|
|
|
+#[derive(Debug, Serialize, Deserialize)]
|
|
|
pub enum DeviceType{
|
|
|
Switch
|
|
|
}
|
|
|
+
|
|
|
+impl User {
|
|
|
+ pub fn read() -> Vec<User> {
|
|
|
+ let path = "/var/lib/ha_permissions/users.json";
|
|
|
+
|
|
|
+ if !Path::new(path).exists() {
|
|
|
+ return Vec::new();
|
|
|
+ }
|
|
|
+
|
|
|
+ let data = fs::read_to_string(path).expect("Failed to read users file");
|
|
|
+
|
|
|
+ if data.trim().is_empty() {
|
|
|
+ return Vec::new();
|
|
|
+ }
|
|
|
+
|
|
|
+ serde_json::from_str(&data).expect("Failed to parse users data")
|
|
|
+ }
|
|
|
+
|
|
|
+ pub fn write(users: Vec<User>) {
|
|
|
+ let path = "/var/lib/ha_permissions/users.json";
|
|
|
+ let data = serde_json::to_string_pretty(&users)
|
|
|
+ .expect("Failed to serialize users");
|
|
|
+
|
|
|
+ if let Some(parent) = Path::new(path).parent() {
|
|
|
+ fs::create_dir_all(parent)
|
|
|
+ .expect("Failed to create directory");
|
|
|
+ }
|
|
|
+
|
|
|
+ let tmp_path = format!("{}.tmp", path);
|
|
|
+ let mut file = fs::File::create(&tmp_path)
|
|
|
+ .expect("Failed to create temp file");
|
|
|
+
|
|
|
+ file.write_all(data.as_bytes())
|
|
|
+ .expect("Failed to write temp file");
|
|
|
+
|
|
|
+ fs::rename(&tmp_path, path)
|
|
|
+ .expect("Failed to replace users file");
|
|
|
+ }
|
|
|
+}
|