1
use actionable::Permissions;
2
use serde::{Deserialize, Serialize};
3

            
4
use crate::{
5
    admin::group,
6
    connection::{AsyncStorageConnection, Connection, IdentityReference, StorageConnection},
7
    define_basic_unique_mapped_view,
8
    document::{CollectionDocument, Emit},
9
    schema::{Collection, Nameable, NamedCollection, SerializedCollection},
10
};
11

            
12
/// An assignable role, which grants permissions based on the associated [`PermissionGroup`](crate::admin::PermissionGroup)s.
13
79825
#[derive(Clone, Debug, Serialize, Deserialize, Collection)]
14
#[collection(name = "role", authority="khonsulabs", views = [ByName], core = crate)]
15
#[must_use]
16
pub struct Role {
17
    /// The name of the role. Must be unique.
18
    pub name: String,
19
    /// The IDs of the permission groups this role belongs to.
20
    pub groups: Vec<u64>,
21
}
22

            
23
impl Role {
24
    /// Returns a new role with no groups and the name provided.
25
8
    pub fn named<S: Into<String>>(name: S) -> Self {
26
8
        Self {
27
8
            name: name.into(),
28
8
            groups: Vec::new(),
29
8
        }
30
8
    }
31

            
32
    /// Builder-style method. Returns self after replacing the current groups with `ids`.
33
    pub fn with_group_ids<I: IntoIterator<Item = u64>>(mut self, ids: I) -> Self {
34
        self.groups = ids.into_iter().collect();
35
        self
36
    }
37

            
38
    pub fn assume_identity<'name, Storage: StorageConnection>(
39
        name_or_id: impl Nameable<'name, u64>,
40
        storage: &Storage,
41
    ) -> Result<Storage::Authenticated, crate::Error> {
42
        storage.assume_identity(IdentityReference::Role(name_or_id.name()?))
43
    }
44

            
45
2
    pub async fn assume_identity_async<'name, Storage: AsyncStorageConnection>(
46
2
        name_or_id: impl Nameable<'name, u64> + Send,
47
2
        storage: &Storage,
48
2
    ) -> Result<Storage::Authenticated, crate::Error> {
49
        storage
50
2
            .assume_identity(IdentityReference::Role(name_or_id.name()?))
51
2
            .await
52
2
    }
53

            
54
    /// Calculates the effective permissions based on the groups this role is assigned.
55
60
    pub fn effective_permissions<C: Connection>(
56
60
        &self,
57
60
        admin: &C,
58
60
        inherit_permissions: &Permissions,
59
60
    ) -> Result<Permissions, crate::Error> {
60
60
        let groups = group::PermissionGroup::get_multiple(&self.groups, admin)?;
61

            
62
        // Combine the permissions from all the groups into one.
63
60
        let merged_permissions = Permissions::merged(
64
60
            groups
65
60
                .into_iter()
66
60
                .map(|group| Permissions::from(group.contents.statements))
67
60
                .collect::<Vec<_>>()
68
60
                .iter()
69
60
                .chain(std::iter::once(inherit_permissions)),
70
60
        );
71
60

            
72
60
        Ok(merged_permissions)
73
60
    }
74
}
75

            
76
impl NamedCollection for Role {
77
    type ByNameView = ByName;
78
}
79

            
80
define_basic_unique_mapped_view!(
81
    ByName,
82
    Role,
83
    1,
84
    "by-name",
85
    String,
86
310
    |document: CollectionDocument<Role>| { document.header.emit_key(document.contents.name) }
87
);