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
50440
#[derive(Clone, Debug, Serialize, Deserialize, Collection)]
11
#[collection(name = "role", authority="khonsulabs", views = [ByName], core = crate)]
12
pub struct Role {
13
    /// The name of the role. Must be unique.
14
    pub name: String,
15
    /// The IDs of the permission groups this role belongs to.
16
    pub groups: Vec<u64>,
17
}
18

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

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

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

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