surrealdb_core/iam/
auth.rsuse crate::sql::statements::{DefineAccessStatement, DefineUserStatement};
use revision::revisioned;
use serde::{Deserialize, Serialize};
use super::{is_allowed, Action, Actor, Error, Level, Resource, Role};
#[revisioned(revision = 1)]
#[derive(Clone, Default, Debug, Eq, PartialEq, PartialOrd, Hash, Serialize, Deserialize)]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
#[non_exhaustive]
pub struct Auth {
actor: Actor,
}
impl Auth {
pub fn new(actor: Actor) -> Self {
Self {
actor,
}
}
pub fn id(&self) -> &str {
self.actor.id()
}
pub fn level(&self) -> &Level {
self.actor.level()
}
pub fn is_anon(&self) -> bool {
matches!(self.level(), Level::No)
}
pub fn is_root(&self) -> bool {
matches!(self.level(), Level::Root)
}
pub fn is_ns(&self) -> bool {
matches!(self.level(), Level::Namespace(_))
}
pub fn is_db(&self) -> bool {
matches!(self.level(), Level::Database(_, _))
}
pub fn is_record(&self) -> bool {
matches!(self.level(), Level::Record(_, _, _))
}
pub fn is_ns_check(&self, ns: &str) -> bool {
matches!(self.level(), Level::Namespace(n) if n.eq(ns))
}
pub fn is_db_check(&self, ns: &str, db: &str) -> bool {
matches!(self.level(), Level::Database(n, d) if n.eq(ns) && d.eq(db))
}
pub fn for_root(role: Role) -> Self {
Self::new(Actor::new("system_auth".into(), vec![role], Level::Root))
}
pub fn for_ns(role: Role, ns: &str) -> Self {
Self::new(Actor::new("system_auth".into(), vec![role], (ns,).into()))
}
pub fn for_db(role: Role, ns: &str, db: &str) -> Self {
Self::new(Actor::new("system_auth".into(), vec![role], (ns, db).into()))
}
pub fn for_record(rid: String, ns: &str, db: &str, ac: &str) -> Self {
Self::new(Actor::new(rid.to_string(), vec![], (ns, db, ac).into()))
}
pub fn is_allowed(&self, action: Action, res: &Resource) -> Result<(), Error> {
is_allowed(&self.actor, &action, res, None)
}
pub fn has_role(&self, role: Role) -> bool {
self.actor.has_role(role)
}
pub fn has_editor_role(&self) -> bool {
self.actor.has_editor_role()
}
pub fn has_viewer_role(&self) -> bool {
self.actor.has_viewer_role()
}
}
impl std::convert::TryFrom<(&DefineUserStatement, Level)> for Auth {
type Error = Error;
fn try_from(val: (&DefineUserStatement, Level)) -> Result<Self, Self::Error> {
Ok(Self::new((val.0, val.1).try_into()?))
}
}
impl std::convert::From<(&DefineAccessStatement, Level)> for Auth {
fn from(val: (&DefineAccessStatement, Level)) -> Self {
Self::new((val.0, val.1).into())
}
}