1
use serde::{Deserialize, Serialize};
2

            
3
use crate::{
4
    define_basic_unique_mapped_view,
5
    document::{CollectionDocument, Emit},
6
    schema::{Collection, NamedCollection},
7
};
8

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

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

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

            
36
impl NamedCollection for Role {
37
    type ByNameView = ByName;
38
}
39

            
40
define_basic_unique_mapped_view!(
41
    ByName,
42
    Role,
43
    1,
44
    "by-name",
45
    String,
46
108
    |document: CollectionDocument<Role>| { document.header.emit_key(document.contents.name) }
47
);