1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
use serde::{Deserialize, Serialize};

use crate::{
    define_basic_unique_mapped_view,
    document::CollectionDocument,
    schema::{Collection, CollectionName, DefaultSerialization, NamedCollection, Schematic},
    Error,
};

/// An assignable role, which grants permissions based on the associated [`PermissionGroup`](crate::admin::PermissionGroup)s.
#[derive(Debug, Serialize, Deserialize)]
pub struct Role {
    /// The name of the role. Must be unique.
    pub name: String,
    /// The IDs of the permission groups this role belongs to.
    pub groups: Vec<u64>,
}

impl Role {
    /// Returns a new role with no groups and the name provided.
    pub fn named<S: Into<String>>(name: S) -> Self {
        Self {
            name: name.into(),
            groups: Vec::new(),
        }
    }

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

impl Collection for Role {
    fn collection_name() -> CollectionName {
        CollectionName::new("khonsulabs", "role")
    }

    fn define_views(schema: &mut Schematic) -> Result<(), Error> {
        schema.define_view(ByName)
    }
}

impl DefaultSerialization for Role {}

impl NamedCollection for Role {
    type ByNameView = ByName;
}

define_basic_unique_mapped_view!(
    ByName,
    Role,
    1,
    "by-name",
    String,
    |document: CollectionDocument<Role>| { document.header.emit_key(document.contents.name) }
);