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