use itertools::Itertools;
use serde::{Deserialize, Serialize};
use crate::admin::{group, role};
use crate::connection::{
AsyncStorageConnection, Connection, IdentityReference, SensitiveString, StorageConnection,
};
use crate::define_basic_unique_mapped_view;
use crate::document::{CollectionDocument, Emit, KeyId};
use crate::permissions::Permissions;
use crate::schema::{Collection, Nameable, NamedCollection, SerializedCollection};
#[derive(Clone, Debug, Serialize, Deserialize, Default, Collection)]
#[collection(name = "user", authority = "khonsulabs", views = [ByName])]
#[collection(encryption_key = Some(KeyId::Master), encryption_optional, core = crate)]
pub struct User {
pub username: String,
pub groups: Vec<u64>,
pub roles: Vec<u64>,
#[serde(default)]
pub argon_hash: Option<SensitiveString>,
}
impl User {
pub fn assume_identity<'name, Storage: StorageConnection>(
name_or_id: impl Nameable<'name, u64>,
storage: &Storage,
) -> Result<Storage::Authenticated, crate::Error> {
storage.assume_identity(IdentityReference::User(name_or_id.name()?))
}
pub async fn assume_identity_async<'name, Storage: AsyncStorageConnection>(
name_or_id: impl Nameable<'name, u64> + Send,
storage: &Storage,
) -> Result<Storage::Authenticated, crate::Error> {
storage
.assume_identity(IdentityReference::User(name_or_id.name()?))
.await
}
pub fn default_with_username(username: impl Into<String>) -> Self {
Self {
username: username.into(),
..Self::default()
}
}
pub fn effective_permissions<C: Connection>(
&self,
admin: &C,
inherit_permissions: &Permissions,
) -> Result<Permissions, crate::Error> {
let role_groups = if self.roles.is_empty() {
Vec::default()
} else {
let roles = role::Role::get_multiple(self.groups.iter(), admin)?;
roles
.into_iter()
.flat_map(|doc| doc.contents.groups)
.unique()
.collect::<Vec<_>>()
};
let groups = if role_groups.is_empty() {
group::PermissionGroup::get_multiple(self.groups.iter(), admin)?
} else {
let mut all_groups = role_groups;
all_groups.extend(self.groups.iter().copied());
all_groups.dedup();
group::PermissionGroup::get_multiple(&all_groups, admin)?
};
let merged_permissions = Permissions::merged(
groups
.into_iter()
.map(|group| Permissions::from(group.contents.statements))
.collect::<Vec<_>>()
.iter()
.chain(std::iter::once(inherit_permissions)),
);
Ok(merged_permissions)
}
}
impl NamedCollection for User {
type ByNameView = ByName;
}
define_basic_unique_mapped_view!(
ByName,
User,
1,
"by-name",
String,
|document: CollectionDocument<User>| { document.header.emit_key(document.contents.username) }
);