add: journals base
add: avatar/banner upload endpoints
This commit is contained in:
parent
b3cac5f97a
commit
bb682add85
14 changed files with 323 additions and 22 deletions
|
@ -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(
|
||||
|
|
|
@ -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<u8> {
|
||||
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<State>,
|
||||
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<State>,
|
||||
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()),
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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",
|
||||
|
|
|
@ -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;
|
||||
|
|
21
crates/core/src/database/common.rs
Normal file
21
crates/core/src/database/common.rs
Normal file
|
@ -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(())
|
||||
}
|
||||
}
|
|
@ -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");
|
||||
|
|
|
@ -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))
|
||||
}
|
||||
}
|
||||
|
||||
|
|
9
crates/core/src/database/drivers/sql/create_pages.sql
Normal file
9
crates/core/src/database/drivers/sql/create_pages.sql
Normal file
|
@ -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
|
||||
)
|
|
@ -15,10 +15,9 @@ impl DataManager {
|
|||
/// Create a new [`DataManager`] (and init database).
|
||||
pub async fn new(config: Config) -> Result<Self> {
|
||||
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)
|
||||
}
|
||||
|
|
|
@ -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::*;
|
||||
|
|
126
crates/core/src/database/pages.rs
Normal file
126
crates/core/src/database/pages.rs
Normal file
|
@ -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<JournalPage> {
|
||||
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(())
|
||||
}
|
||||
}
|
|
@ -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);
|
||||
|
||||
|
|
52
crates/core/src/model/journal.rs
Normal file
52
crates/core/src/model/journal.rs
Normal file
|
@ -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
|
||||
}
|
||||
}
|
|
@ -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(),
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue