session.rs 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  1. use anyhow::{Context, Result};
  2. use serde::{Deserialize, Serialize};
  3. use std::fs;
  4. use std::path::PathBuf;
  5. use crate::models::UserInfo;
  6. /// Session data stored to disk
  7. #[derive(Debug, Clone, Serialize, Deserialize)]
  8. pub struct SessionData {
  9. pub server_url: String,
  10. pub token: String,
  11. pub user: UserInfo,
  12. pub remember_server: bool,
  13. pub remember_username: bool,
  14. pub saved_username: Option<String>,
  15. #[serde(default)]
  16. pub default_printer_id: Option<i64>,
  17. /// Remember last-used printer (may differ from default_printer_id if user overrides per-print)
  18. #[serde(default)]
  19. pub last_printer_id: Option<i64>,
  20. }
  21. /// Manages user session and credentials
  22. pub struct SessionManager {
  23. config_path: PathBuf,
  24. current_session: Option<SessionData>,
  25. }
  26. impl SessionManager {
  27. /// Create a new session manager
  28. pub fn new() -> Self {
  29. let config_dir = dirs::config_dir()
  30. .unwrap_or_else(|| PathBuf::from("."))
  31. .join("beepzone");
  32. // Ensure config directory exists
  33. let _ = fs::create_dir_all(&config_dir);
  34. let config_path = config_dir.join("session.json");
  35. let mut manager = Self {
  36. config_path,
  37. current_session: None,
  38. };
  39. // Try to load existing session
  40. let _ = manager.load_session();
  41. manager
  42. }
  43. /// Save a new session
  44. pub fn save_session(&mut self, session: SessionData) -> Result<()> {
  45. self.current_session = Some(session.clone());
  46. let json = serde_json::to_string_pretty(&session).context("Failed to serialize session")?;
  47. fs::write(&self.config_path, json).context("Failed to write session file")?;
  48. log::info!("Session saved to {:?}", self.config_path);
  49. Ok(())
  50. }
  51. /// Load session from disk
  52. pub fn load_session(&mut self) -> Result<()> {
  53. if !self.config_path.exists() {
  54. return Ok(());
  55. }
  56. let json = fs::read_to_string(&self.config_path).context("Failed to read session file")?;
  57. let session: SessionData =
  58. serde_json::from_str(&json).context("Failed to parse session file")?;
  59. self.current_session = Some(session);
  60. log::info!("Session loaded from {:?}", self.config_path);
  61. Ok(())
  62. }
  63. /// Clear the current session
  64. pub fn clear_session(&mut self) -> Result<()> {
  65. self.current_session = None;
  66. if self.config_path.exists() {
  67. fs::remove_file(&self.config_path).context("Failed to remove session file")?;
  68. log::info!("Session file removed");
  69. }
  70. Ok(())
  71. }
  72. /// Get the current session
  73. pub fn get_session(&self) -> Option<&SessionData> {
  74. self.current_session.as_ref()
  75. }
  76. /// Check if there's a valid session
  77. #[allow(dead_code)]
  78. pub fn has_session(&self) -> bool {
  79. self.current_session.is_some()
  80. }
  81. /// Get the saved server URL (if remember_server is enabled)
  82. pub fn get_saved_server_url(&self) -> Option<String> {
  83. self.current_session
  84. .as_ref()
  85. .filter(|s| s.remember_server)
  86. .map(|s| s.server_url.clone())
  87. }
  88. /// Get the saved username (if remember_username is enabled)
  89. pub fn get_saved_username(&self) -> Option<String> {
  90. self.current_session
  91. .as_ref()
  92. .and_then(|s| s.saved_username.clone())
  93. }
  94. /// Update session with new token (for token refresh)
  95. #[allow(dead_code)]
  96. pub fn update_token(&mut self, new_token: String) -> Result<()> {
  97. if let Some(session) = &mut self.current_session {
  98. let mut updated_session = session.clone();
  99. updated_session.token = new_token;
  100. self.save_session(updated_session)?;
  101. }
  102. Ok(())
  103. }
  104. /// Update default printer ID
  105. pub fn update_default_printer(&mut self, printer_id: Option<i64>) -> Result<()> {
  106. if let Some(session) = &mut self.current_session {
  107. let mut updated_session = session.clone();
  108. updated_session.default_printer_id = printer_id;
  109. self.save_session(updated_session)?;
  110. }
  111. Ok(())
  112. }
  113. /// Get default printer ID
  114. pub fn get_default_printer_id(&self) -> Option<i64> {
  115. self.current_session
  116. .as_ref()
  117. .and_then(|s| s.default_printer_id)
  118. }
  119. /// Get last-used printer ID for printing
  120. pub fn get_last_print_preferences(&self) -> Option<i64> {
  121. if let Some(session) = &self.current_session {
  122. session.last_printer_id
  123. } else {
  124. None
  125. }
  126. }
  127. }
  128. impl Default for SessionManager {
  129. fn default() -> Self {
  130. Self::new()
  131. }
  132. }