From bb682add85b3a7a3a843c7ecaaa448928c6b1b7a Mon Sep 17 00:00:00 2001 From: trisua Date: Sun, 23 Mar 2025 18:03:11 -0400 Subject: [PATCH] add: journals base add: avatar/banner upload endpoints --- crates/app/src/main.rs | 5 +- crates/app/src/routes/api/v1/auth/images.rs | 88 +++++++++++- crates/app/src/routes/api/v1/mod.rs | 8 ++ crates/core/src/database/auth.rs | 7 +- crates/core/src/database/common.rs | 21 +++ crates/core/src/database/drivers/common.rs | 1 + crates/core/src/database/drivers/postgres.rs | 12 +- .../src/database/drivers/sql/create_pages.sql | 9 ++ crates/core/src/database/drivers/sqlite.rs | 3 +- crates/core/src/database/mod.rs | 4 +- crates/core/src/database/pages.rs | 126 ++++++++++++++++++ crates/core/src/model/auth.rs | 3 +- crates/core/src/model/journal.rs | 52 ++++++++ crates/core/src/model/mod.rs | 6 + 14 files changed, 323 insertions(+), 22 deletions(-) create mode 100644 crates/core/src/database/common.rs create mode 100644 crates/core/src/database/drivers/sql/create_pages.sql create mode 100644 crates/core/src/database/pages.rs create mode 100644 crates/core/src/model/journal.rs diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs index ae0e79d..b9cd5b0 100644 --- a/crates/app/src/main.rs +++ b/crates/app/src/main.rs @@ -30,10 +30,13 @@ async fn main() { let html_path = write_assets(&config).await; // ... + let database = DataManager::new(config.clone()).await.unwrap(); + database.init().await.unwrap(); + let app = Router::new() .merge(routes::routes(&config)) .layer(Extension(Arc::new(RwLock::new(( - DataManager::new(config.clone()).await.unwrap(), + database, Tera::new(&format!("{html_path}/**/*")).unwrap(), ))))) .layer( diff --git a/crates/app/src/routes/api/v1/auth/images.rs b/crates/app/src/routes/api/v1/auth/images.rs index e092881..40389a4 100644 --- a/crates/app/src/routes/api/v1/auth/images.rs +++ b/crates/app/src/routes/api/v1/auth/images.rs @@ -1,11 +1,17 @@ -use axum::{Extension, body::Body, extract::Path, response::IntoResponse}; -use pathbufd::PathBufD; +use axum::{Extension, Json, body::Body, extract::Path, response::IntoResponse}; +use axum_extra::extract::CookieJar; +use pathbufd::{PathBufD, pathd}; use std::{ fs::{File, exists}, io::Read, }; +use tetratto_core::model::{ApiReturn, Error}; -use crate::State; +use crate::{ + State, + avif::{Image, save_avif_buffer}, + get_user_from_token, +}; pub fn read_image(path: PathBufD) -> Vec { let mut bytes = Vec::new(); @@ -100,3 +106,79 @@ pub async fn banner_request( Body::from(read_image(path)), ) } + +static MAXIUMUM_FILE_SIZE: usize = 8388608; + +/// Upload avatar +pub async fn upload_avatar_request( + jar: CookieJar, + Extension(data): Extension, + img: Image, +) -> impl IntoResponse { + // get user from token + let data = &(data.read().await).0; + let auth_user = match get_user_from_token!(jar, data) { + Some(ua) => ua, + None => return Json(Error::NotAllowed.into()), + }; + + let path = pathd!("{}/avatars/{}.avif", data.0.dirs.media, &auth_user.id); + + // check file size + if img.0.len() > MAXIUMUM_FILE_SIZE { + return Json(Error::DataTooLong("image".to_string()).into()); + } + + // upload image + let mut bytes = Vec::new(); + + for byte in img.0 { + bytes.push(byte); + } + + match save_avif_buffer(&path, bytes) { + Ok(_) => Json(ApiReturn { + ok: true, + message: "Avatar uploaded. It might take a bit to update".to_string(), + payload: (), + }), + Err(e) => Json(Error::MiscError(e.to_string()).into()), + } +} + +/// Upload banner +pub async fn upload_banner_request( + jar: CookieJar, + Extension(data): Extension, + img: Image, +) -> impl IntoResponse { + // get user from token + let data = &(data.read().await).0; + let auth_user = match get_user_from_token!(jar, data) { + Some(ua) => ua, + None => return Json(Error::NotAllowed.into()), + }; + + let path = pathd!("{}/banners/{}.avif", data.0.dirs.media, &auth_user.id); + + // check file size + if img.0.len() > MAXIUMUM_FILE_SIZE { + return Json(Error::DataTooLong("image".to_string()).into()); + } + + // upload image + let mut bytes = Vec::new(); + + for byte in img.0 { + bytes.push(byte); + } + + match save_avif_buffer(&path, bytes) { + Ok(_) => Json(ApiReturn { + ok: true, + message: "Banner uploaded. It might take a bit to update".to_string(), + payload: (), + }), + Err(e) => Json(Error::MiscError(e.to_string()).into()), + } +} diff --git a/crates/app/src/routes/api/v1/mod.rs b/crates/app/src/routes/api/v1/mod.rs index b927576..1952bc0 100644 --- a/crates/app/src/routes/api/v1/mod.rs +++ b/crates/app/src/routes/api/v1/mod.rs @@ -12,6 +12,14 @@ pub fn routes() -> Router { .route("/auth/register", post(auth::register_request)) .route("/auth/login", post(auth::login_request)) .route("/auth/logout", post(auth::logout_request)) + .route( + "/auth/upload/avatar", + post(auth::images::upload_avatar_request), + ) + .route( + "/auth/upload/banner", + post(auth::images::upload_banner_request), + ) // profile .route( "/auth/profile/{id}/avatar", diff --git a/crates/core/src/database/auth.rs b/crates/core/src/database/auth.rs index 445ab2f..53c05d1 100644 --- a/crates/core/src/database/auth.rs +++ b/crates/core/src/database/auth.rs @@ -1,6 +1,9 @@ use super::*; -use crate::model::permissions::FinePermission; -use crate::model::{Error, Result}; +use crate::model::{ + Error, Result, + auth::{Token, User}, + permissions::FinePermission, +}; use crate::{execute, get, query_row}; use tetratto_shared::hash::hash_salted; diff --git a/crates/core/src/database/common.rs b/crates/core/src/database/common.rs new file mode 100644 index 0000000..1ff2615 --- /dev/null +++ b/crates/core/src/database/common.rs @@ -0,0 +1,21 @@ +use crate::{ + database::drivers::common, + execute, + model::{Error, Result}, +}; + +use super::DataManager; + +impl DataManager { + pub async fn init(&self) -> Result<()> { + let conn = match self.connect().await { + Ok(c) => c, + Err(e) => return Err(Error::DatabaseConnection(e.to_string())), + }; + + execute!(&conn, common::CREATE_TABLE_USERS, []).unwrap(); + execute!(&conn, common::CREATE_TABLE_PAGES, []).unwrap(); + + Ok(()) + } +} diff --git a/crates/core/src/database/drivers/common.rs b/crates/core/src/database/drivers/common.rs index bdd1240..483e797 100644 --- a/crates/core/src/database/drivers/common.rs +++ b/crates/core/src/database/drivers/common.rs @@ -1 +1,2 @@ pub const CREATE_TABLE_USERS: &str = include_str!("./sql/create_users.sql"); +pub const CREATE_TABLE_PAGES: &str = include_str!("./sql/create_pages.sql"); diff --git a/crates/core/src/database/drivers/postgres.rs b/crates/core/src/database/drivers/postgres.rs index 5f25907..ed1a6f1 100644 --- a/crates/core/src/database/drivers/postgres.rs +++ b/crates/core/src/database/drivers/postgres.rs @@ -34,17 +34,9 @@ impl DataManager { }, NoTls, ); + let pool = Pool::builder().max_size(15).build(manager).await.unwrap(); - - let this = Self(config.clone(), read_langs(), pool); - let c = this.clone(); - let conn = c.connect().await?; - - conn.execute(super::common::CREATE_TABLE_USERS, &[]) - .await - .unwrap(); - - Ok(this) + Ok(Self(config.clone(), read_langs(), pool)) } } diff --git a/crates/core/src/database/drivers/sql/create_pages.sql b/crates/core/src/database/drivers/sql/create_pages.sql new file mode 100644 index 0000000..e107ae7 --- /dev/null +++ b/crates/core/src/database/drivers/sql/create_pages.sql @@ -0,0 +1,9 @@ +CREATE TABLE IF NOT EXISTS pages ( + id INTEGER NOT NULL PRIMARY KEY, + created INTEGER NOT NULL, + title TEXT NOT NULL, + prompt TEXT NOT NULL, + owner TEXT NOT NULL, + read_access TEXT NOT NULL, + write_access TEXT NOT NULL +) diff --git a/crates/core/src/database/drivers/sqlite.rs b/crates/core/src/database/drivers/sqlite.rs index 052b623..cd07d80 100644 --- a/crates/core/src/database/drivers/sqlite.rs +++ b/crates/core/src/database/drivers/sqlite.rs @@ -15,10 +15,9 @@ impl DataManager { /// Create a new [`DataManager`] (and init database). pub async fn new(config: Config) -> Result { let this = Self(config.clone(), read_langs()); - let conn = this.connect().await?; + let conn = this.connect().await?; conn.pragma_update(None, "journal_mode", "WAL").unwrap(); - conn.execute(super::common::CREATE_TABLE_USERS, ()).unwrap(); Ok(this) } diff --git a/crates/core/src/database/mod.rs b/crates/core/src/database/mod.rs index c1f2804..eef7761 100644 --- a/crates/core/src/database/mod.rs +++ b/crates/core/src/database/mod.rs @@ -1,7 +1,7 @@ mod auth; +mod common; mod drivers; - -use super::model::auth::{Token, User}; +mod pages; #[cfg(feature = "sqlite")] pub use drivers::sqlite::*; diff --git a/crates/core/src/database/pages.rs b/crates/core/src/database/pages.rs new file mode 100644 index 0000000..b1961ab --- /dev/null +++ b/crates/core/src/database/pages.rs @@ -0,0 +1,126 @@ +use super::*; +use crate::model::auth::User; +use crate::model::{Error, Result, journal::JournalPage, permissions::FinePermission}; +use crate::{execute, get, query_row}; + +#[cfg(feature = "sqlite")] +use rusqlite::Row; + +#[cfg(feature = "postgres")] +use tokio_postgres::Row; + +impl DataManager { + /// Get a [`JournalPage`] from an SQL row. + pub(crate) fn get_page_from_row( + #[cfg(feature = "sqlite")] x: &Row<'_>, + #[cfg(feature = "postgres")] x: &Row, + ) -> JournalPage { + JournalPage { + id: get!(x->0(u64)) as usize, + created: get!(x->1(u64)) as usize, + title: get!(x->2(String)), + prompt: get!(x->3(String)), + owner: get!(x->4(u64)) as usize, + read_access: serde_json::from_str(&get!(x->5(String)).to_string()).unwrap(), + write_access: serde_json::from_str(&get!(x->6(String)).to_string()).unwrap(), + } + } + + /// Get a journal page given just its `id`. + /// + /// # Arguments + /// * `id` - the ID of the page + pub async fn get_page_by_id(&self, id: &str) -> Result { + let conn = match self.connect().await { + Ok(c) => c, + Err(e) => return Err(Error::DatabaseConnection(e.to_string())), + }; + + let res = query_row!(&conn, "SELECT * FROM pages WHERE id = $1", &[&id], |x| { + Ok(Self::get_page_from_row(x)) + }); + + if res.is_err() { + return Err(Error::GeneralNotFound("journal page".to_string())); + } + + Ok(res.unwrap()) + } + + /// Create a new journal page in the database. + /// + /// # Arguments + /// * `data` - a mock [`JournalPage`] object to insert + pub async fn create_page(&self, data: JournalPage) -> Result<()> { + if self.0.security.registration_enabled == false { + return Err(Error::RegistrationDisabled); + } + + // check values + if data.title.len() < 2 { + return Err(Error::DataTooShort("title".to_string())); + } else if data.title.len() > 32 { + return Err(Error::DataTooLong("username".to_string())); + } + + if data.prompt.len() < 2 { + return Err(Error::DataTooShort("prompt".to_string())); + } else if data.prompt.len() > 2048 { + return Err(Error::DataTooLong("prompt".to_string())); + } + + // ... + let conn = match self.connect().await { + Ok(c) => c, + Err(e) => return Err(Error::DatabaseConnection(e.to_string())), + }; + + let res = execute!( + &conn, + "INSERT INTO pages VALUES ($1, $2, $3, $4, $5, $6, $7)", + &[ + &data.id.to_string().as_str(), + &data.created.to_string().as_str(), + &data.title.as_str(), + &data.prompt.as_str(), + &data.owner.to_string().as_str(), + &serde_json::to_string(&data.read_access).unwrap().as_str(), + &serde_json::to_string(&data.write_access).unwrap().as_str(), + ] + ); + + if let Err(e) = res { + return Err(Error::DatabaseError(e.to_string())); + } + + Ok(()) + } + + /// Create a new user in the database. + /// + /// # Arguments + /// * `id` - the ID of the page + /// * `user` - the user deleting the page + pub async fn delete_page(&self, id: &str, user: User) -> Result<()> { + let page = self.get_page_by_id(id).await?; + + if user.id != page.owner { + if !user.permissions.check(FinePermission::MANAGE_JOURNAL_PAGES) { + return Err(Error::NotAllowed); + } + } + + let conn = match self.connect().await { + Ok(c) => c, + Err(e) => return Err(Error::DatabaseConnection(e.to_string())), + }; + + let res = execute!(&conn, "DELETE FROM pages WHERE id = $1", &[&id]); + + if let Err(e) = res { + return Err(Error::DatabaseError(e.to_string())); + } + + Ok(()) + } +} diff --git a/crates/core/src/model/auth.rs b/crates/core/src/model/auth.rs index 0bf3df8..5700325 100644 --- a/crates/core/src/model/auth.rs +++ b/crates/core/src/model/auth.rs @@ -1,3 +1,4 @@ +use super::permissions::FinePermission; use serde::{Deserialize, Serialize}; use tetratto_shared::{ hash::{hash_salted, salt}, @@ -5,8 +6,6 @@ use tetratto_shared::{ unix_epoch_timestamp, }; -use super::permissions::FinePermission; - /// `(ip, token, creation timestamp)` pub type Token = (String, String, usize); diff --git a/crates/core/src/model/journal.rs b/crates/core/src/model/journal.rs new file mode 100644 index 0000000..7c1393a --- /dev/null +++ b/crates/core/src/model/journal.rs @@ -0,0 +1,52 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Serialize, Deserialize)] +pub struct JournalPage { + pub id: usize, + pub created: usize, + pub title: String, + pub prompt: String, + /// The ID of the owner of the journal page. + pub owner: usize, + /// Who can read the journal page. + pub read_access: JournalPageReadAccess, + /// Who can write to the journal page (create journal entries belonging to it). + /// + /// The owner of the journal page (and moderators) are the ***only*** people + /// capable of removing entries. + pub write_access: JournalPageWriteAccess, +} + +/// Who can read a [`JournalPage`]. +#[derive(Serialize, Deserialize)] +pub enum JournalPageReadAccess { + /// Everybody can view the journal page from the owner's profile. + Everybody, + /// Only people with the link to the journal page. + Unlisted, + /// Only the owner of the journal page. + Private, +} + +impl Default for JournalPageReadAccess { + fn default() -> Self { + Self::Everybody + } +} + +/// Who can write to a [`JournalPage`]. +#[derive(Serialize, Deserialize)] +pub enum JournalPageWriteAccess { + /// Everybody (authenticated + anonymous users). + Everybody, + /// Authenticated users only. + Authenticated, + /// Only the owner of the journal page. + Owner, +} + +impl Default for JournalPageWriteAccess { + fn default() -> Self { + Self::Authenticated + } +} diff --git a/crates/core/src/model/mod.rs b/crates/core/src/model/mod.rs index b3af128..ca9a31b 100644 --- a/crates/core/src/model/mod.rs +++ b/crates/core/src/model/mod.rs @@ -1,5 +1,7 @@ pub mod auth; +pub mod journal; pub mod permissions; + use serde::{Deserialize, Serialize}; #[derive(Serialize, Deserialize)] @@ -14,8 +16,10 @@ where #[derive(Debug)] pub enum Error { + MiscError(String), DatabaseConnection(String), UserNotFound, + GeneralNotFound(String), RegistrationDisabled, DatabaseError(String), IncorrectPassword, @@ -29,9 +33,11 @@ pub enum Error { impl ToString for Error { fn to_string(&self) -> String { match self { + Self::MiscError(msg) => msg.to_owned(), Self::DatabaseConnection(msg) => msg.to_owned(), Self::DatabaseError(msg) => format!("Database error: {msg}"), Self::UserNotFound => "Unable to find user with given parameters".to_string(), + Self::GeneralNotFound(name) => format!("Unable to find requested {name}"), Self::RegistrationDisabled => "Registration is disabled".to_string(), Self::IncorrectPassword => "The given password is invalid".to_string(), Self::NotAllowed => "You are not allowed to do this".to_string(),