pastry/src/database/users.rs
2025-08-30 11:27:44 -04:00

161 lines
5.5 KiB
Rust

use super::DataManager;
use crate::{
database::NAME_REGEX,
model::{User, UserSession, UserSettings},
};
use oiseau::{PostgresRow, cache::Cache, execute, get, params, query_row};
use tetratto_core::{
auto_method,
model::{Error, Result},
};
use tetratto_shared::{
hash::{hash, salt},
unix_epoch_timestamp,
};
impl DataManager {
/// Get a [`User`] from an SQL row.
pub(crate) fn get_user_from_row(x: &PostgresRow) -> User {
User {
id: get!(x->0(String)),
created: get!(x->1(i64)) as usize,
username: get!(x->2(String)),
password: get!(x->3(String)),
salt: get!(x->4(String)),
sessions: serde_json::from_str(&get!(x->5(String))).unwrap(),
username_changed: get!(x->6(i64)) as usize,
role: serde_json::from_str(&get!(x->7(String))).unwrap(),
banned: get!(x->8(i32)) == 1,
settings: serde_json::from_str(&get!(x->8(String))).unwrap(),
legacy_token: get!(x->9(String)),
}
}
auto_method!(get_user_by_id(usize as i64)@get_user_from_row -> "SELECT * FROM p_users WHERE id = $1" --name="user" --returns=User --cache-key-tmpl="pstr.user:{}");
auto_method!(get_user_by_username(&str)@get_user_from_row -> "SELECT * FROM p_users WHERE username = $1" --name="user" --returns=User --cache-key-tmpl="pstr.user:{}");
/// Create a new user in the database.
///
/// # Arguments
/// * `data` - a mock [`User`] object to insert
pub async fn create_user(&self, data: User) -> Result<User> {
// check values
if data.username.trim().len() < 2 {
return Err(Error::DataTooShort("username".to_string()));
} else if data.username.len() > 32 {
return Err(Error::DataTooLong("username".to_string()));
}
// check characters
let regex = regex::RegexBuilder::new(NAME_REGEX)
.multi_line(true)
.build()
.unwrap();
if regex.captures(&data.username).is_some() {
return Err(Error::MiscError(
"Username contains invalid characters".to_string(),
));
}
// ...
let conn = match self.0.connect().await {
Ok(c) => c,
Err(e) => return Err(Error::DatabaseConnection(e.to_string())),
};
let res = execute!(
&conn,
"INSERT INTO p_users VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)",
params![
&data.id,
&(data.created as i64),
&data.username,
&data.password,
&data.salt,
&serde_json::to_string(&data.sessions).unwrap(),
&(data.username_changed as i64),
&serde_json::to_string(&data.role).unwrap(),
&if data.banned { 1_i32 } else { 0_i32 },
&serde_json::to_string(&data.settings).unwrap(),
&data.legacy_token
]
);
if let Err(e) = res {
return Err(Error::DatabaseError(e.to_string()));
}
Ok(data)
}
pub async fn update_user_password(&self, id: usize, x: String) -> Result<()> {
let y = self.get_user_by_id(id).await?;
let new_salt = salt();
let hashed = hash(x + &new_salt);
let conn = match self.0.connect().await {
Ok(c) => c,
Err(e) => return Err(Error::DatabaseConnection(e.to_string())),
};
let res = execute!(
&conn,
"UPDATE users SET password = $1, salt = $2 WHERE id = $2",
params![&hashed, &new_salt, &(id as i64)]
);
if let Err(e) = res {
return Err(Error::DatabaseError(e.to_string()));
}
self.cache_clear_user(&y).await;
Ok(())
}
const USERNAME_CHANGE_WAIT_TIME: usize = 604800000; // 1 week
pub async fn update_user_username(&self, id: usize, x: String) -> Result<()> {
let y = self.get_user_by_id(id).await?;
let now = unix_epoch_timestamp();
if now - y.username_changed < Self::USERNAME_CHANGE_WAIT_TIME {
return Err(Error::MiscError(
"Username changed too recently".to_string(),
));
}
let conn = match self.0.connect().await {
Ok(c) => c,
Err(e) => return Err(Error::DatabaseConnection(e.to_string())),
};
let res = execute!(
&conn,
"UPDATE users SET username = $1, username_changed = $2 WHERE id = $2",
params![&x, &(now as i64), &(id as i64)]
);
if let Err(e) = res {
return Err(Error::DatabaseError(e.to_string()));
}
self.cache_clear_user(&y).await;
Ok(())
}
pub async fn cache_clear_user(&self, user: &User) -> bool {
self.0.1.remove(format!("pstr.user:{}", user.id)).await
&& self
.0
.1
.remove(format!("pstr.user:{}", user.username))
.await
}
auto_method!(update_user_banned(i32)@get_user_by_id -> "UPDATE users SET banned = $1 WHERE id = $2" --cache-key-tmpl=cache_clear_user);
auto_method!(update_user_settings(UserSettings)@get_user_by_id -> "UPDATE users SET settings = $1 WHERE id = $2" --serde --cache-key-tmpl=cache_clear_user);
auto_method!(update_user_sessions(Vec<UserSession>)@get_user_by_id -> "UPDATE users SET sessions = $1 WHERE id = $2" --serde --cache-key-tmpl=cache_clear_user);
}