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