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
5383999
    fn check_permission<'a, R: AsRef<[Identifier<'a>]>, P: Action>(
25
5383999
        &self,
26
5383999
        resource_name: R,
27
5383999
        action: &P,
28
5383999
    ) -> Result<(), Error> {
29
5383999
        self.session().map_or_else(
30
5383999
            || Ok(()),
31
5383999
            |session| session.check_permission(resource_name, action),
32
5383999
        )
33
5383999
    }
34
}