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
79825
#[derive(Clone, Debug, Serialize, Deserialize, Collection)]
12
#[collection(name = "permission-group", authority="khonsulabs", views = [ByName], core = crate)]
13
#[must_use]
14
pub struct PermissionGroup {
15
    /// The name of the group. Must be unique.
16
    pub name: String,
17
    /// The permission statements.
18
    pub statements: Vec<Statement>,
19
}
20

            
21
impl PermissionGroup {
22
    /// Returns a new group with no statements and the name provided.
23
8
    pub fn named<S: Into<String>>(name: S) -> Self {
24
8
        Self {
25
8
            name: name.into(),
26
8
            statements: Vec::new(),
27
8
        }
28
8
    }
29

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

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

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