1
use actionable::{Action, Identifier};
2

            
3
use crate::{connection::Session, Error};
4

            
5
/// Functions to access information about the current session (authentication).
6
pub trait HasSession {
7
    /// Returns the currently authenticated session, if any.
8
    fn session(&self) -> Option<&Session>;
9

            
10
    /// Checks if `action` is permitted against `resource_name`.
11
    fn allowed_to<'a, R: AsRef<[Identifier<'a>]>, P: Action>(
12
        &self,
13
        resource_name: R,
14
        action: &P,
15
    ) -> bool {
16
        self.session()
17
            .map_or(true, |session| session.allowed_to(resource_name, action))
18
    }
19

            
20
    /// Checks if `action` is permitted against `resource_name`. If permission
21
    /// is denied, returns a [`PermissionDenied`](Error::PermissionDenied)
22
    /// error.
23
4084807
    fn check_permission<'a, R: AsRef<[Identifier<'a>]>, P: Action>(
24
4084807
        &self,
25
4084807
        resource_name: R,
26
4084807
        action: &P,
27
4084807
    ) -> Result<(), Error> {
28
4084807
        self.session().map_or_else(
29
4084807
            || Ok(()),
30
4084807
            |session| session.check_permission(resource_name, action),
31
4084807
        )
32
4084807
    }
33
}