1
use itertools::Itertools;
2
use serde::{Deserialize, Serialize};
3

            
4
use crate::{
5
    admin::{group, role},
6
    connection::{
7
        AsyncStorageConnection, Connection, IdentityReference, SensitiveString, StorageConnection,
8
    },
9
    define_basic_unique_mapped_view,
10
    document::{CollectionDocument, Emit, KeyId},
11
    permissions::Permissions,
12
    schema::{Collection, Nameable, NamedCollection, SerializedCollection},
13
};
14

            
15
/// A user that can authenticate with BonsaiDb.
16
159650
#[derive(Clone, Debug, Serialize, Deserialize, Default, Collection)]
17
#[collection(name = "user", authority = "khonsulabs", views = [ByName])]
18
#[collection(encryption_key = Some(KeyId::Master), encryption_optional, core = crate)]
19
pub struct User {
20
    /// The name of the role. Must be unique.
21
    pub username: String,
22
    /// The IDs of the user groups this user belongs to.
23
    pub groups: Vec<u64>,
24
    /// The IDs of the roles this user has been assigned.
25
    pub roles: Vec<u64>,
26

            
27
    /// The user's stored password hash.
28
    ///
29
    /// This field is not feature gated to prevent losing stored passwords if
30
    /// the `password-hashing` feature is disabled and then re-enabled and user
31
    /// records are updated in the meantime.
32
    #[serde(default)]
33
    pub argon_hash: Option<SensitiveString>,
34
}
35

            
36
impl User {
37
    pub fn assume_identity<'name, Storage: StorageConnection>(
38
        name_or_id: impl Nameable<'name, u64>,
39
        storage: &Storage,
40
    ) -> Result<Storage::Authenticated, crate::Error> {
41
        storage.assume_identity(IdentityReference::User(name_or_id.name()?))
42
    }
43

            
44
    pub async fn assume_identity_async<'name, Storage: AsyncStorageConnection>(
45
        name_or_id: impl Nameable<'name, u64> + Send,
46
        storage: &Storage,
47
    ) -> Result<Storage::Authenticated, crate::Error> {
48
        storage
49
            .assume_identity(IdentityReference::User(name_or_id.name()?))
50
            .await
51
    }
52

            
53
    /// Returns a default user with the given username.
54
274
    pub fn default_with_username(username: impl Into<String>) -> Self {
55
274
        Self {
56
274
            username: username.into(),
57
274
            ..Self::default()
58
274
        }
59
274
    }
60

            
61
    /// Calculates the effective permissions based on the groups and roles this
62
    /// user is assigned.
63
150
    pub fn effective_permissions<C: Connection>(
64
150
        &self,
65
150
        admin: &C,
66
150
        inherit_permissions: &Permissions,
67
150
    ) -> Result<Permissions, crate::Error> {
68
        // List all of the groups that this user belongs to because of role associations.
69
150
        let role_groups = if self.roles.is_empty() {
70
150
            Vec::default()
71
        } else {
72
            let roles = role::Role::get_multiple(self.groups.iter(), admin)?;
73
            roles
74
                .into_iter()
75
                .flat_map(|doc| doc.contents.groups)
76
                .unique()
77
                .collect::<Vec<_>>()
78
        };
79
        // Retrieve all of the groups.
80
150
        let groups = if role_groups.is_empty() {
81
150
            group::PermissionGroup::get_multiple(self.groups.iter(), admin)?
82
        } else {
83
            let mut all_groups = role_groups;
84
            all_groups.extend(self.groups.iter().copied());
85
            all_groups.dedup();
86
            group::PermissionGroup::get_multiple(all_groups, admin)?
87
        };
88

            
89
        // Combine the permissions from all the groups into one.
90
150
        let merged_permissions = Permissions::merged(
91
150
            groups
92
150
                .into_iter()
93
150
                .map(|group| Permissions::from(group.contents.statements))
94
150
                .collect::<Vec<_>>()
95
150
                .iter()
96
150
                .chain(std::iter::once(inherit_permissions)),
97
150
        );
98
150

            
99
150
        Ok(merged_permissions)
100
150
    }
101
}
102

            
103
impl NamedCollection for User {
104
    type ByNameView = ByName;
105
}
106

            
107
define_basic_unique_mapped_view!(
108
    ByName,
109
    User,
110
    1,
111
    "by-name",
112
    String,
113
1550
    |document: CollectionDocument<User>| { document.header.emit_key(document.contents.username) }
114
);