use std::collections::HashSet;
#[derive(Debug, Clone)]
pub struct Identity {
subject: String,
auth_method: &'static str,
display_name: Option<String>,
scopes: HashSet<String>,
service_account: bool,
privileged: bool,
attributes: http::Extensions,
}
impl Identity {
#[must_use]
pub fn new(subject: impl Into<String>, auth_method: &'static str) -> Self {
Self {
subject: subject.into(),
auth_method,
display_name: None,
scopes: HashSet::new(),
service_account: false,
privileged: false,
attributes: http::Extensions::new(),
}
}
pub fn builder(subject: impl Into<String>, auth_method: &'static str) -> IdentityBuilder {
IdentityBuilder {
identity: Self::new(subject, auth_method),
}
}
#[must_use]
pub fn subject(&self) -> &str {
&self.subject
}
#[must_use]
pub const fn auth_method(&self) -> &'static str {
self.auth_method
}
#[must_use]
pub fn display_name(&self) -> Option<&str> {
self.display_name.as_deref()
}
#[must_use]
pub const fn scopes(&self) -> &HashSet<String> {
&self.scopes
}
#[must_use]
pub const fn is_privileged(&self) -> bool {
self.privileged
}
#[must_use]
pub const fn is_service_account(&self) -> bool {
self.service_account
}
#[must_use]
pub const fn attributes(&self) -> &http::Extensions {
&self.attributes
}
pub const fn attributes_mut(&mut self) -> &mut http::Extensions {
&mut self.attributes
}
pub const fn set_privileged(&mut self, privileged: bool) {
self.privileged = privileged;
}
pub const fn set_service_account(&mut self, service_account: bool) {
self.service_account = service_account;
}
#[must_use]
pub fn has_scope(&self, scope: &str) -> bool {
self.scopes.contains(scope)
}
#[must_use]
pub fn has_all_scopes(&self, scopes: &[&str]) -> bool {
scopes.iter().all(|s| self.scopes.contains(*s))
}
#[must_use]
pub fn has_any_scope(&self, scopes: &[&str]) -> bool {
scopes.iter().any(|s| self.scopes.contains(*s))
}
}
#[derive(Debug)]
#[must_use = "IdentityBuilder must be consumed by .build() to produce an Identity"]
pub struct IdentityBuilder {
identity: Identity,
}
impl IdentityBuilder {
pub fn display_name(mut self, name: impl Into<String>) -> Self {
self.identity.display_name = Some(name.into());
self
}
pub fn scope(mut self, scope: impl Into<String>) -> Self {
self.identity.scopes.insert(scope.into());
self
}
pub fn scopes(mut self, scopes: impl IntoIterator<Item = impl Into<String>>) -> Self {
self.identity
.scopes
.extend(scopes.into_iter().map(Into::into));
self
}
pub const fn privileged(mut self, privileged: bool) -> Self {
self.identity.privileged = privileged;
self
}
pub const fn service_account(mut self, service_account: bool) -> Self {
self.identity.service_account = service_account;
self
}
pub fn attribute<T: Clone + Send + Sync + 'static>(mut self, value: T) -> Self {
self.identity.attributes.insert(value);
self
}
#[must_use]
pub fn build(self) -> Identity {
self.identity
}
}