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

            
3
use crate::connection::Session;
4
use crate::Error;
5

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

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

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