Echo Writes Code

state.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
use crate::content::{ ContentDatabase, Permission };
use crate::errors::{ Error, Result };
use crate::renderer::{ Renderer };
use std::path::{ Path };
use std::sync::{ RwLock, RwLockReadGuard, RwLockWriteGuard };

#[derive(Debug)]
pub struct ServerState {
  database: RwLock<ContentDatabase>,
  renderer: Renderer,
}

impl ServerState {
  pub fn new(site_title: &str, content_path: &Path, metadata_path: &Path, theme_path: &Path) -> Result<ServerState> {
    let database = ContentDatabase::new(content_path, metadata_path)?;
    let server_state = ServerState {
      database: RwLock::new(database),
      renderer: Renderer::new(site_title, theme_path)?,
    };

    Ok(server_state)
  }

  pub fn check_access(&self, required_permissions: &[Permission], session_permissions: Option<Vec<Permission>>) -> Result<()> {
    #[allow(clippy::collapsible_if)]
    if let Some(anonymous_permissions) = self.database().anonymous_permissions() {
      if required_permissions.iter().all(|p| anonymous_permissions.contains(p)) {
        return Ok(());
      }
    }

    #[allow(clippy::collapsible_if)]
    if let Some(session_permissions) = session_permissions {
      if required_permissions.iter().all(|p| session_permissions.contains(p)) {
        return Ok(());
      }
    }

    Err(Error::PermissionDenied)
  }

  pub fn database(&self) -> RwLockReadGuard<'_, ContentDatabase> {
    self.database
      .read()
      .expect("Database lock should not be poisoned")
  }

  pub fn database_mut(&self) -> RwLockWriteGuard<'_, ContentDatabase> {
    self.database
      .write()
      .expect("Database lock should not be poisoned")
  }

  pub fn renderer(&self) -> &Renderer {
    &self.renderer
  }
}