surrealdb_core/dbs/
session.rsuse crate::ctx::MutableContext;
use crate::iam::Auth;
use crate::iam::{Level, Role};
use crate::sql::value::Value;
use chrono::Utc;
use std::sync::Arc;
#[derive(Clone, Debug, Default, Eq, PartialEq)]
#[non_exhaustive]
pub struct Session {
pub au: Arc<Auth>,
pub rt: bool,
pub ip: Option<String>,
pub or: Option<String>,
pub id: Option<String>,
pub ns: Option<String>,
pub db: Option<String>,
pub ac: Option<String>,
pub tk: Option<Value>,
pub rd: Option<Value>,
pub exp: Option<i64>,
}
impl Session {
pub fn with_ns(mut self, ns: &str) -> Session {
self.ns = Some(ns.to_owned());
self
}
pub fn with_db(mut self, db: &str) -> Session {
self.db = Some(db.to_owned());
self
}
pub fn with_ac(mut self, ac: &str) -> Session {
self.ac = Some(ac.to_owned());
self
}
pub fn with_rt(mut self, rt: bool) -> Session {
self.rt = rt;
self
}
pub(crate) fn ns(&self) -> Option<Arc<str>> {
self.ns.as_deref().map(Into::into)
}
pub(crate) fn db(&self) -> Option<Arc<str>> {
self.db.as_deref().map(Into::into)
}
pub(crate) fn live(&self) -> bool {
self.rt
}
pub(crate) fn expired(&self) -> bool {
match self.exp {
Some(exp) => Utc::now().timestamp() > exp,
None => false,
}
}
pub(crate) fn context(&self, ctx: &mut MutableContext) {
let val: Value = self.ac.to_owned().into();
ctx.add_value("access", val.into());
let val: Value = self.rd.to_owned().into();
ctx.add_value("auth", val.into());
let val: Value = self.tk.to_owned().into();
ctx.add_value("token", val.into());
let val: Value = Value::from(map! {
"ac".to_string() => self.ac.to_owned().into(),
"exp".to_string() => self.exp.to_owned().into(),
"db".to_string() => self.db.to_owned().into(),
"id".to_string() => self.id.to_owned().into(),
"ip".to_string() => self.ip.to_owned().into(),
"ns".to_string() => self.ns.to_owned().into(),
"or".to_string() => self.or.to_owned().into(),
"rd".to_string() => self.rd.to_owned().into(),
"tk".to_string() => self.tk.to_owned().into(),
});
ctx.add_value("session", val.into());
}
pub fn for_level(level: Level, role: Role) -> Session {
let mut sess = Session::default();
match level {
Level::Root => {
sess.au = Arc::new(Auth::for_root(role));
}
Level::Namespace(ns) => {
sess.au = Arc::new(Auth::for_ns(role, &ns));
sess.ns = Some(ns);
}
Level::Database(ns, db) => {
sess.au = Arc::new(Auth::for_db(role, &ns, &db));
sess.ns = Some(ns);
sess.db = Some(db);
}
_ => {}
}
sess
}
pub fn for_record(ns: &str, db: &str, ac: &str, rid: Value) -> Session {
Session {
ac: Some(ac.to_owned()),
au: Arc::new(Auth::for_record(rid.to_string(), ns, db, ac)),
rt: false,
ip: None,
or: None,
id: None,
ns: Some(ns.to_owned()),
db: Some(db.to_owned()),
tk: None,
rd: Some(rid),
exp: None,
}
}
pub fn owner() -> Session {
Session::for_level(Level::Root, Role::Owner)
}
pub fn editor() -> Session {
Session::for_level(Level::Root, Role::Editor)
}
pub fn viewer() -> Session {
Session::for_level(Level::Root, Role::Viewer)
}
}