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

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

            
10
/// A named group of permissions statements.
11
50440
#[derive(Clone, Debug, Serialize, Deserialize, Collection)]
12
#[collection(name = "permission-group", authority="khonsulabs", views = [ByName], core = crate)]
13
pub struct PermissionGroup {
14
    /// The name of the group. Must be unique.
15
    pub name: String,
16
    /// The permission statements.
17
    pub statements: Vec<Statement>,
18
}
19

            
20
impl PermissionGroup {
21
    /// Returns a new group with no statements 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
            statements: Vec::new(),
26
4
        }
27
4
    }
28

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

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

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