surrealdb_sql/statements/define/
user.rsuse crate::ctx::Context;
use crate::dbs::{Options, Transaction};
use crate::doc::CursorDoc;
use crate::err::Error;
use crate::iam::{Action, ResourceKind};
use crate::{escape::quote_str, fmt::Fmt, Base, Ident, Strand, Value};
use argon2::{
password_hash::{PasswordHasher, SaltString},
Argon2,
};
use derive::Store;
use rand::{distributions::Alphanumeric, rngs::OsRng, Rng};
use revision::revisioned;
use serde::{Deserialize, Serialize};
use std::fmt::{self, Display};
#[derive(Clone, Debug, Default, Eq, PartialEq, PartialOrd, Serialize, Deserialize, Store, Hash)]
#[revisioned(revision = 1)]
pub struct DefineUserStatement {
pub name: Ident,
pub base: Base,
pub hash: String,
pub code: String,
pub roles: Vec<Ident>,
pub comment: Option<Strand>,
}
impl From<(Base, &str, &str)> for DefineUserStatement {
fn from((base, user, pass): (Base, &str, &str)) -> Self {
DefineUserStatement {
base,
name: user.into(),
hash: Argon2::default()
.hash_password(pass.as_ref(), &SaltString::generate(&mut OsRng))
.unwrap()
.to_string(),
code: rand::thread_rng()
.sample_iter(&Alphanumeric)
.take(128)
.map(char::from)
.collect::<String>(),
roles: vec!["owner".into()],
comment: None,
}
}
}
impl DefineUserStatement {
#[doc(hidden)]
pub async fn compute(
&self,
_ctx: &Context<'_>,
opt: &Options,
txn: &Transaction,
_doc: Option<&CursorDoc<'_>>,
) -> Result<Value, Error> {
opt.is_allowed(Action::Edit, ResourceKind::Actor, &self.base)?;
match self.base {
Base::Root => {
let mut run = txn.lock().await;
run.clear_cache();
let key = crate::key::root::us::new(&self.name);
run.set(key, self).await?;
Ok(Value::None)
}
Base::Ns => {
let mut run = txn.lock().await;
run.clear_cache();
let key = crate::key::namespace::us::new(opt.ns(), &self.name);
run.add_ns(opt.ns(), opt.strict).await?;
run.set(key, self).await?;
Ok(Value::None)
}
Base::Db => {
let mut run = txn.lock().await;
run.clear_cache();
let key = crate::key::database::us::new(opt.ns(), opt.db(), &self.name);
run.add_ns(opt.ns(), opt.strict).await?;
run.add_db(opt.ns(), opt.db(), opt.strict).await?;
run.set(key, self).await?;
Ok(Value::None)
}
_ => Err(Error::InvalidLevel(self.base.to_string())),
}
}
}
impl Display for DefineUserStatement {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"DEFINE USER {} ON {} PASSHASH {} ROLES {}",
self.name,
self.base,
quote_str(&self.hash),
Fmt::comma_separated(
&self.roles.iter().map(|r| r.to_string().to_uppercase()).collect::<Vec<String>>()
)
)?;
if let Some(ref v) = self.comment {
write!(f, " COMMENT {v}")?
}
Ok(())
}
}