Compare commits
2 Commits
314c1bec7d
...
4ea44b3639
Author | SHA1 | Date |
---|---|---|
SadlyNotSappho | 4ea44b3639 | |
SadlyNotSappho | bfb63afa7e |
|
@ -597,6 +597,7 @@ version = "0.1.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"base64",
|
"base64",
|
||||||
"image",
|
"image",
|
||||||
|
"markdown",
|
||||||
"rand",
|
"rand",
|
||||||
"rand_hc",
|
"rand_hc",
|
||||||
"regex",
|
"regex",
|
||||||
|
@ -1095,6 +1096,15 @@ dependencies = [
|
||||||
"tracing-subscriber",
|
"tracing-subscriber",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "markdown"
|
||||||
|
version = "1.0.0-alpha.16"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "5b0f0025e8c0d89b84d6dc63e859475e40e8e82ab1a08be0a93ad5731513a508"
|
||||||
|
dependencies = [
|
||||||
|
"unicode-id",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "matchers"
|
name = "matchers"
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
|
@ -2589,6 +2599,12 @@ version = "0.3.14"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "6f2528f27a9eb2b21e69c95319b30bd0efd85d09c379741b0f78ea1d86be2416"
|
checksum = "6f2528f27a9eb2b21e69c95319b30bd0efd85d09c379741b0f78ea1d86be2416"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "unicode-id"
|
||||||
|
version = "0.3.4"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "b1b6def86329695390197b82c1e244a54a131ceb66c996f2088a3876e2ae083f"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "unicode-ident"
|
name = "unicode-ident"
|
||||||
version = "1.0.12"
|
version = "1.0.12"
|
||||||
|
|
|
@ -8,6 +8,7 @@ edition = "2021"
|
||||||
[dependencies]
|
[dependencies]
|
||||||
base64 = "0.21.7"
|
base64 = "0.21.7"
|
||||||
image = "0.24.8"
|
image = "0.24.8"
|
||||||
|
markdown = "1.0.0-alpha.16"
|
||||||
rand = "0.8.5"
|
rand = "0.8.5"
|
||||||
rand_hc = "0.3.2"
|
rand_hc = "0.3.2"
|
||||||
regex = "1.10.3"
|
regex = "1.10.3"
|
||||||
|
|
|
@ -1 +1,3 @@
|
||||||
pub mod tables;
|
pub mod tables;
|
||||||
|
|
||||||
|
pub mod routes;
|
||||||
|
|
562
src/main.rs
562
src/main.rs
|
@ -1,17 +1,11 @@
|
||||||
use image::io::Reader;
|
|
||||||
use rocket::fairing::AdHoc;
|
use rocket::fairing::AdHoc;
|
||||||
use rocket::fs::{FileServer, NamedFile};
|
use rocket::fs::FileServer;
|
||||||
use rocket::http::Status;
|
use rocket::http::Status;
|
||||||
use rocket::response::content::{self, RawHtml};
|
use rocket::response::content::{self, RawHtml};
|
||||||
use rocket::response::status;
|
|
||||||
use rocket::serde::Serialize;
|
|
||||||
use rocket::{Build, Request, Rocket};
|
use rocket::{Build, Request, Rocket};
|
||||||
use rocket_db_pools::sqlx::pool::PoolConnection;
|
use rocket_db_pools::sqlx::pool::PoolConnection;
|
||||||
use rocket_db_pools::sqlx::Postgres;
|
use rocket_db_pools::sqlx::Postgres;
|
||||||
use rocket_db_pools::Connection;
|
|
||||||
use std::fs;
|
use std::fs;
|
||||||
use std::path::Path;
|
|
||||||
use uuid::Uuid;
|
|
||||||
#[macro_use]
|
#[macro_use]
|
||||||
extern crate rocket;
|
extern crate rocket;
|
||||||
|
|
||||||
|
@ -20,518 +14,8 @@ use rocket_db_pools::{
|
||||||
Database,
|
Database,
|
||||||
};
|
};
|
||||||
|
|
||||||
use rocket::fs::TempFile;
|
use fossil::routes;
|
||||||
use rocket::http::CookieJar;
|
use fossil::tables::{Db, Post};
|
||||||
use rocket::serde::{json::Json, Deserialize};
|
|
||||||
|
|
||||||
use fossil::tables::{Db, Image, LoginStatus, Post, User};
|
|
||||||
|
|
||||||
#[get("/login")]
|
|
||||||
fn login_page() -> RawHtml<String> {
|
|
||||||
RawHtml(fs::read_to_string("/srv/web/login.html").unwrap())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[get("/createuser")]
|
|
||||||
fn createuser_page() -> RawHtml<String> {
|
|
||||||
RawHtml(fs::read_to_string("/srv/web/createuser.html").unwrap())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[get("/uploadimage")]
|
|
||||||
fn uploadimage() -> RawHtml<String> {
|
|
||||||
RawHtml(fs::read_to_string("/srv/web/uploadimage.html").unwrap())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[get("/myimages")]
|
|
||||||
fn myimages() -> RawHtml<String> {
|
|
||||||
RawHtml(fs::read_to_string("/srv/web/myimages.html").unwrap())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
|
||||||
#[serde(crate = "rocket::serde")]
|
|
||||||
struct LoginInfo {
|
|
||||||
username: String,
|
|
||||||
password: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[post("/createuser", data = "<info>")]
|
|
||||||
async fn createuser(
|
|
||||||
mut db: Connection<Db>,
|
|
||||||
info: Json<LoginInfo>,
|
|
||||||
cookies: &CookieJar<'_>,
|
|
||||||
) -> status::Custom<String> {
|
|
||||||
let token = cookies.get_private("token");
|
|
||||||
match token.is_some() {
|
|
||||||
true => status::Custom(
|
|
||||||
Status::Forbidden,
|
|
||||||
"You're already logged in. Log out before trying to create a new account.".to_string(),
|
|
||||||
),
|
|
||||||
false => match User::get_by_username(&mut db, &info.username).await {
|
|
||||||
Some(_) => status::Custom(
|
|
||||||
Status::Forbidden,
|
|
||||||
"Username already taken. Please try again.".to_string(),
|
|
||||||
),
|
|
||||||
None => match User::create(&mut db, &info.username, &info.password).await {
|
|
||||||
Ok(_) => match User::get_by_username(&mut db, &info.username).await {
|
|
||||||
Some(user) => match user.set_new_token(&mut db).await {
|
|
||||||
Ok(t) => {
|
|
||||||
cookies.add_private(("token", t));
|
|
||||||
status::Custom(Status::Ok, "Your account has been created and you've been automatically logged in.".to_string())
|
|
||||||
}
|
|
||||||
Err(why) => {
|
|
||||||
eprintln!("{why:?}");
|
|
||||||
status::Custom(
|
|
||||||
Status::Created,
|
|
||||||
"Couldn't log you in. Your account has been created, though."
|
|
||||||
.to_string(),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
},
|
|
||||||
None => status::Custom(
|
|
||||||
Status::InternalServerError,
|
|
||||||
"Something went really wrong. I don't know what.".to_string(),
|
|
||||||
),
|
|
||||||
},
|
|
||||||
Err(why) => {
|
|
||||||
format!("Couldn't create user: {}", why);
|
|
||||||
status::Custom(Status::InternalServerError, format!("{why}"))
|
|
||||||
}
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Serialize)]
|
|
||||||
#[serde(crate = "rocket::serde")]
|
|
||||||
struct GetUser {
|
|
||||||
username: String,
|
|
||||||
admin: bool,
|
|
||||||
make_posts: bool,
|
|
||||||
comment: bool,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[get("/account")]
|
|
||||||
async fn account(
|
|
||||||
mut db: Connection<Db>,
|
|
||||||
cookies: &CookieJar<'_>,
|
|
||||||
) -> status::Custom<Result<Json<GetUser>, &'static str>> {
|
|
||||||
let token = cookies.get_private("token");
|
|
||||||
match token {
|
|
||||||
Some(t) => match User::get_by_token(&mut db, t).await {
|
|
||||||
Some(user) => status::Custom(
|
|
||||||
Status::Ok,
|
|
||||||
Ok(Json(GetUser {
|
|
||||||
username: user.username,
|
|
||||||
admin: user.admin,
|
|
||||||
make_posts: user.make_posts,
|
|
||||||
comment: user.comment,
|
|
||||||
})),
|
|
||||||
),
|
|
||||||
None => status::Custom(Status::NotFound, Err("User doesn't exist.")),
|
|
||||||
},
|
|
||||||
None => status::Custom(Status::Unauthorized, Err("Not logged in")),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[post("/login", data = "<info>")]
|
|
||||||
async fn login(
|
|
||||||
mut db: Connection<Db>,
|
|
||||||
info: Json<LoginInfo>,
|
|
||||||
cookies: &CookieJar<'_>,
|
|
||||||
) -> status::Custom<&'static str> {
|
|
||||||
let token = cookies.get_private("token");
|
|
||||||
match token {
|
|
||||||
Some(_) => {
|
|
||||||
status::Custom(Status::Continue, "already logged in")
|
|
||||||
}
|
|
||||||
None => {
|
|
||||||
match User::get_by_username(&mut db, &info.username).await {
|
|
||||||
Some(user) => {
|
|
||||||
if user.password == sha256::digest(&info.password) {
|
|
||||||
match user.token {
|
|
||||||
Some(t) => {cookies.add_private(("token", t)); status::Custom(Status::Ok, "Logged in")},
|
|
||||||
None => {
|
|
||||||
match user.set_new_token(&mut db).await {
|
|
||||||
Ok(t) => {
|
|
||||||
cookies.add_private(("token", t));
|
|
||||||
status::Custom(Status::Ok, "Logged in")
|
|
||||||
},
|
|
||||||
Err(why) => {
|
|
||||||
eprintln!("{why:?}");
|
|
||||||
status::Custom(Status::InternalServerError, "Couldn't generate a token for you, therefore you weren't logged in.")
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
status::Custom(Status::Forbidden, "Invalid username or password (to those whining about why it doesn't tell you if the username or password is incorrect, security)")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
None =>
|
|
||||||
status::Custom(Status::Forbidden, "Invalid username or password (to those whining about why it doesn't tell you if the username or password is incorrect, security)")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[post("/logout")]
|
|
||||||
async fn logout(cookies: &CookieJar<'_>) -> status::Custom<&'static str> {
|
|
||||||
match cookies.get_private("token") {
|
|
||||||
Some(_) => {
|
|
||||||
cookies.remove_private("token");
|
|
||||||
status::Custom(Status::Ok, "Logged out.")
|
|
||||||
}
|
|
||||||
None => status::Custom(Status::Unauthorized, "Not logged in."),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[get("/adminpanel")]
|
|
||||||
async fn adminpanel(
|
|
||||||
mut db: Connection<Db>,
|
|
||||||
cookies: &CookieJar<'_>,
|
|
||||||
) -> status::Custom<RawHtml<String>> {
|
|
||||||
let token = cookies.get_private("token");
|
|
||||||
match token {
|
|
||||||
Some(t) => match User::get_by_token(&mut db, t).await {
|
|
||||||
Some(user) => match user.admin {
|
|
||||||
true => status::Custom(
|
|
||||||
Status::Ok,
|
|
||||||
RawHtml(
|
|
||||||
fs::read_to_string("/srv/web/adminpanel.html")
|
|
||||||
.unwrap()
|
|
||||||
.replace("{{username}}", &user.username[..]),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
false => status::Custom(
|
|
||||||
Status::Unauthorized,
|
|
||||||
RawHtml(fs::read_to_string("/srv/web/invalidperms.html").unwrap()),
|
|
||||||
),
|
|
||||||
},
|
|
||||||
None => status::Custom(
|
|
||||||
Status::Unauthorized,
|
|
||||||
RawHtml(
|
|
||||||
fs::read_to_string("/srv/web/error.html")
|
|
||||||
.unwrap()
|
|
||||||
.replace("{{errorcode}}", "401"),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
},
|
|
||||||
None => status::Custom(
|
|
||||||
Status::Unauthorized,
|
|
||||||
RawHtml(fs::read_to_string("/srv/web/invalidperms.html").unwrap()),
|
|
||||||
),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// #[derive(Deserialize, Serialize)]
|
|
||||||
// #[serde(crate = "rocket::serde")]
|
|
||||||
// struct ApiPermsResult {
|
|
||||||
// perms: Result<Perms, String>,
|
|
||||||
// }
|
|
||||||
#[derive(Deserialize, Serialize)]
|
|
||||||
#[serde(crate = "rocket::serde")]
|
|
||||||
struct Perms {
|
|
||||||
admin: bool,
|
|
||||||
make_posts: bool,
|
|
||||||
comment: bool,
|
|
||||||
}
|
|
||||||
#[get("/perms/<username>")]
|
|
||||||
async fn api_perms(
|
|
||||||
mut db: Connection<Db>,
|
|
||||||
username: String,
|
|
||||||
cookies: &CookieJar<'_>,
|
|
||||||
) -> status::Custom<Json<Result<Perms, &'static str>>> {
|
|
||||||
match cookies.get_private("token") {
|
|
||||||
Some(t) => match User::get_by_token(&mut db, t).await {
|
|
||||||
Some(user) => match user.admin {
|
|
||||||
true => match User::get_by_username(&mut db, &username).await {
|
|
||||||
Some(user) => status::Custom(
|
|
||||||
Status::Ok,
|
|
||||||
Json(Ok(Perms {
|
|
||||||
admin: user.admin,
|
|
||||||
make_posts: user.make_posts,
|
|
||||||
comment: user.comment,
|
|
||||||
})),
|
|
||||||
),
|
|
||||||
None => status::Custom(Status::NotFound, Json(Err("User doesn't exist"))),
|
|
||||||
},
|
|
||||||
false => status::Custom(
|
|
||||||
Status::Unauthorized,
|
|
||||||
Json(Err("You don't have the permission to do this")),
|
|
||||||
),
|
|
||||||
},
|
|
||||||
None => status::Custom(Status::Unauthorized, Json(Err("Invalid token"))),
|
|
||||||
},
|
|
||||||
None => status::Custom(Status::Unauthorized, Json(Err("Not logged in"))),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
|
||||||
#[serde(crate = "rocket::serde")]
|
|
||||||
struct TogglePerms {
|
|
||||||
perm: String,
|
|
||||||
value: bool,
|
|
||||||
username: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[post("/toggleperms", data = "<info>")]
|
|
||||||
async fn toggleperms(
|
|
||||||
mut db: Connection<Db>,
|
|
||||||
info: Json<TogglePerms>,
|
|
||||||
cookies: &CookieJar<'_>,
|
|
||||||
) -> status::Custom<String> {
|
|
||||||
match cookies.get_private("token") {
|
|
||||||
Some(t) => {
|
|
||||||
match User::get_by_token(&mut db, t).await {
|
|
||||||
Some(user) => {
|
|
||||||
match user.admin {
|
|
||||||
true => match User::get_by_username(&mut db, &info.username).await {
|
|
||||||
Some(toggled_user) => {
|
|
||||||
match toggled_user.username == user.username && info.perm == "admin"
|
|
||||||
{
|
|
||||||
true => status::Custom(
|
|
||||||
Status::Forbidden,
|
|
||||||
"You can't change your own admin status".to_string(),
|
|
||||||
),
|
|
||||||
false => {
|
|
||||||
let admin_username = std::env::var("ADMIN_USERNAME")
|
|
||||||
.expect("set ADMIN_USERNAME env var");
|
|
||||||
match toggled_user.username == admin_username {
|
|
||||||
true => status::Custom(
|
|
||||||
Status::Forbidden,
|
|
||||||
"You can't change the system admin's perms."
|
|
||||||
.to_string(),
|
|
||||||
),
|
|
||||||
false => {
|
|
||||||
match info.perm == "admin"
|
|
||||||
&& user.username != admin_username
|
|
||||||
{
|
|
||||||
true => status::Custom(
|
|
||||||
Status::Forbidden,
|
|
||||||
"You can't change other people's admin status."
|
|
||||||
.to_string(),
|
|
||||||
),
|
|
||||||
false => {
|
|
||||||
match toggled_user.set_role(&mut db,&info.perm,&info.value).await {
|
|
||||||
Ok(_) => status::Custom(Status::Ok, "Done".to_string()),
|
|
||||||
Err(why) => status::Custom(Status::InternalServerError, format!(
|
|
||||||
"Couldn't update the user's role: {why}"
|
|
||||||
)),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
None => status::Custom(
|
|
||||||
Status::NotFound,
|
|
||||||
"The user you're trying to toggle perms for doesn't exist."
|
|
||||||
.to_string(),
|
|
||||||
),
|
|
||||||
},
|
|
||||||
false => {
|
|
||||||
status::Custom(Status::Unauthorized, "You aren't an admin.".to_string())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
None => status::Custom(Status::Unauthorized, "Invalid login token".to_string()),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
None => status::Custom(Status::Unauthorized, "Not logged in".to_string()),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[get("/images/<image>")]
|
|
||||||
async fn get_image(
|
|
||||||
image: String,
|
|
||||||
mut db: Connection<Db>,
|
|
||||||
) -> Result<NamedFile, status::Custom<&'static str>> {
|
|
||||||
let mut split = image.split('.').collect::<Vec<&str>>();
|
|
||||||
let format = split.pop().unwrap();
|
|
||||||
let image = split.join(".");
|
|
||||||
|
|
||||||
match Image::get_by_uuid(&mut db, &image).await {
|
|
||||||
Ok(_) => match Reader::open(format!("/srv/images/{image}.png")) {
|
|
||||||
Ok(i) => match i.decode() {
|
|
||||||
Ok(img) => {
|
|
||||||
let encoder = match format {
|
|
||||||
"jpg" => image::ImageFormat::Jpeg,
|
|
||||||
"jpeg" => image::ImageFormat::Jpeg,
|
|
||||||
"png" => image::ImageFormat::Png,
|
|
||||||
_ => {
|
|
||||||
panic!("invalid format")
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
img.save_with_format(format!("/tmp/{image}.{format}"), encoder)
|
|
||||||
.unwrap();
|
|
||||||
let file = NamedFile::open(Path::new(&format!("/tmp/{image}.{format}")))
|
|
||||||
.await
|
|
||||||
.unwrap();
|
|
||||||
fs::remove_file(format!("/tmp/{image}.{format}")).unwrap_or(());
|
|
||||||
|
|
||||||
Ok(file)
|
|
||||||
}
|
|
||||||
Err(why) => Err(match &why.to_string()[..] {
|
|
||||||
"Format error decoding Png: Invalid PNG signature." => {
|
|
||||||
status::Custom(Status::NotAcceptable, "That file isn't an image.")
|
|
||||||
}
|
|
||||||
_ => status::Custom(Status::InternalServerError, "Unknown decoding error"),
|
|
||||||
}),
|
|
||||||
},
|
|
||||||
Err(_) => Err(status::Custom(
|
|
||||||
Status::InternalServerError,
|
|
||||||
"Unknown decoding error",
|
|
||||||
)),
|
|
||||||
},
|
|
||||||
Err(_) => Err(status::Custom(
|
|
||||||
Status::InternalServerError,
|
|
||||||
"File not found",
|
|
||||||
)),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[post("/upload", format = "image/png", data = "<file>")]
|
|
||||||
async fn upload(
|
|
||||||
mut file: TempFile<'_>,
|
|
||||||
cookies: &CookieJar<'_>,
|
|
||||||
mut db: Connection<Db>,
|
|
||||||
) -> status::Custom<String> {
|
|
||||||
let uuid = Uuid::new_v4().to_string();
|
|
||||||
|
|
||||||
// login & perms check
|
|
||||||
match User::login_status(&mut db, cookies).await {
|
|
||||||
LoginStatus::LoggedIn(user) => {
|
|
||||||
match user.make_posts || user.admin {
|
|
||||||
// image validation check
|
|
||||||
true => {
|
|
||||||
match file.copy_to(format!("/srv/tmpimages/{uuid}.png")).await {
|
|
||||||
Ok(_) => {
|
|
||||||
// validate that it is, in fact, an image
|
|
||||||
match Reader::open(format!("/srv/tmpimages/{uuid}.png")) {
|
|
||||||
Ok(_) => {
|
|
||||||
match file.copy_to(format!("/srv/images/{uuid}.png")).await {
|
|
||||||
Ok(_) => match Image::create(&mut db, &uuid, user).await {
|
|
||||||
Ok(_) => {
|
|
||||||
match fs::remove_file(format!(
|
|
||||||
"/srv/tmpimages/{uuid}.png"
|
|
||||||
)) {
|
|
||||||
Ok(_) => status::Custom(Status::Created, uuid),
|
|
||||||
Err(why) => {
|
|
||||||
eprintln!("couldn't clear image from tmpimages: {why:?}");
|
|
||||||
status::Custom(Status::Ok, uuid)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Err(why) => {
|
|
||||||
eprintln!("{why:?}");
|
|
||||||
status::Custom(
|
|
||||||
Status::InternalServerError,
|
|
||||||
"Couldn't save to DB".to_string(),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
},
|
|
||||||
Err(_) => status::Custom(
|
|
||||||
Status::InternalServerError,
|
|
||||||
"Couldn't copy file to final location".to_string(),
|
|
||||||
),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Err(_) => status::Custom(
|
|
||||||
Status::Forbidden,
|
|
||||||
"File isn't an image".to_string(),
|
|
||||||
),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Err(_) => status::Custom(
|
|
||||||
Status::InternalServerError,
|
|
||||||
"Couldn't save temporary file".to_string(),
|
|
||||||
),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
false => status::Custom(
|
|
||||||
Status::Unauthorized,
|
|
||||||
"You don't have the right permissions for that".to_string(),
|
|
||||||
),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
LoginStatus::InvalidToken => {
|
|
||||||
status::Custom(Status::Unauthorized, "Invalid login token".to_string())
|
|
||||||
}
|
|
||||||
LoginStatus::NotLoggedIn => {
|
|
||||||
status::Custom(Status::Unauthorized, "Not logged in".to_string())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[delete("/images/<uuid>")]
|
|
||||||
pub async fn delete_image(
|
|
||||||
mut db: Connection<Db>,
|
|
||||||
cookies: &CookieJar<'_>,
|
|
||||||
uuid: String,
|
|
||||||
) -> status::Custom<&'static str> {
|
|
||||||
match User::login_status(&mut db, cookies).await {
|
|
||||||
LoginStatus::LoggedIn(user) => {
|
|
||||||
match Image::is_owned_by(&mut db, &uuid, &user.username).await {
|
|
||||||
Ok(b) => match b {
|
|
||||||
// yeah this is jank but fuck types i don't want to figure that out
|
|
||||||
true => delimg(&mut db, uuid).await,
|
|
||||||
false => match user.admin {
|
|
||||||
true => delimg(&mut db, uuid).await,
|
|
||||||
false => status::Custom(Status::Unauthorized, "You don't own that image"),
|
|
||||||
},
|
|
||||||
},
|
|
||||||
Err(_) => status::Custom(Status::NotFound, "Couldn't get image"),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
LoginStatus::InvalidToken => status::Custom(Status::Unauthorized, "Invalid login token"),
|
|
||||||
LoginStatus::NotLoggedIn => status::Custom(Status::Unauthorized, "Not logged in"),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn delimg(db: &mut Connection<Db>, uuid: String) -> status::Custom<&'static str> {
|
|
||||||
match Image::delete(db, &uuid).await {
|
|
||||||
Ok(_) => match fs::remove_file(format!("/srv/images/{uuid}.png")) {
|
|
||||||
Ok(_) => status::Custom(Status::Ok, "Image deleted"),
|
|
||||||
Err(why) => {
|
|
||||||
eprintln!("{why:?}");
|
|
||||||
status::Custom(
|
|
||||||
Status::ImATeapot,
|
|
||||||
"Image deleted from database but not filesystem",
|
|
||||||
)
|
|
||||||
}
|
|
||||||
},
|
|
||||||
Err(_) => status::Custom(Status::InternalServerError, "Couldn't delete the image"),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[get("/images/by-user/<username>")]
|
|
||||||
pub async fn get_images_by_username(
|
|
||||||
mut db: Connection<Db>,
|
|
||||||
cookies: &CookieJar<'_>,
|
|
||||||
username: String,
|
|
||||||
) -> Result<Json<Vec<String>>, String> {
|
|
||||||
let token = cookies.get_private("token");
|
|
||||||
match token {
|
|
||||||
Some(t) => match User::get_by_token(&mut db, t).await {
|
|
||||||
Some(user) => match user.admin || user.username == username {
|
|
||||||
true => match Image::get_by_username(&mut db, &username).await {
|
|
||||||
Ok(images) => Ok(Json::from(
|
|
||||||
images.into_iter().map(|i| i.uuid).collect::<Vec<String>>(),
|
|
||||||
)),
|
|
||||||
Err(why) => {
|
|
||||||
eprintln!("{why:?}");
|
|
||||||
Err("Couldn't get that user's images".to_string())
|
|
||||||
}
|
|
||||||
},
|
|
||||||
false => Err("You don't have permission to do this".to_string()),
|
|
||||||
},
|
|
||||||
None => Err("Invalid login token".to_string()),
|
|
||||||
},
|
|
||||||
None => Err("Not logged in".to_string()),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[catch(default)]
|
#[catch(default)]
|
||||||
fn default_catcher(status: Status, _: &Request) -> RawHtml<String> {
|
fn default_catcher(status: Status, _: &Request) -> RawHtml<String> {
|
||||||
|
@ -626,6 +110,13 @@ async fn migrate(rocket: Rocket<Build>) -> Rocket<Build> {
|
||||||
))
|
))
|
||||||
.await;
|
.await;
|
||||||
|
|
||||||
|
let _ = conn
|
||||||
|
.execute(sqlx::query(
|
||||||
|
"ALTER TABLE posts
|
||||||
|
ADD COLUMN IF NOT EXISTS uuid TEXT NOT NULL UNIQUE,
|
||||||
|
ADD COLUMN IF NOT EXISTS text_id TEXT NOT NULL UNIQUE",
|
||||||
|
))
|
||||||
|
.await;
|
||||||
rocket
|
rocket
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -650,23 +141,26 @@ async fn main() {
|
||||||
.mount(
|
.mount(
|
||||||
"/",
|
"/",
|
||||||
routes![
|
routes![
|
||||||
login_page,
|
// gets from /web
|
||||||
login,
|
routes::web::login_page,
|
||||||
logout,
|
routes::web::uploadimage,
|
||||||
createuser,
|
routes::web::createuser_page,
|
||||||
createuser_page,
|
routes::web::myimages,
|
||||||
account,
|
// user related stuff
|
||||||
adminpanel,
|
routes::users::login,
|
||||||
toggleperms,
|
routes::users::logout,
|
||||||
get_image,
|
routes::users::createuser,
|
||||||
upload,
|
routes::users::account,
|
||||||
uploadimage,
|
routes::users::adminpanel,
|
||||||
delete_image,
|
routes::users::toggleperms,
|
||||||
get_images_by_username,
|
// image related stuff
|
||||||
myimages
|
routes::images::get_image,
|
||||||
|
routes::images::upload,
|
||||||
|
routes::images::delete_image,
|
||||||
|
routes::images::get_images_by_username,
|
||||||
],
|
],
|
||||||
)
|
)
|
||||||
.mount("/api", routes![api_perms])
|
.mount("/api", routes![routes::users::api_perms])
|
||||||
.mount("/css", FileServer::from("/srv/web/css"))
|
.mount("/css", FileServer::from("/srv/web/css"))
|
||||||
.register("/", catchers![default_catcher])
|
.register("/", catchers![default_catcher])
|
||||||
.launch()
|
.launch()
|
||||||
|
|
|
@ -0,0 +1,204 @@
|
||||||
|
use crate::tables::{Db, Image, LoginStatus, User};
|
||||||
|
use image::io::Reader;
|
||||||
|
use rocket::fs::NamedFile;
|
||||||
|
use rocket::fs::TempFile;
|
||||||
|
use rocket::http::CookieJar;
|
||||||
|
use rocket::http::Status;
|
||||||
|
use rocket::response::status;
|
||||||
|
use rocket::serde::json::Json;
|
||||||
|
use rocket::{delete, get, post};
|
||||||
|
use rocket_db_pools::Connection;
|
||||||
|
use std::fs;
|
||||||
|
use std::path::Path;
|
||||||
|
use uuid::Uuid;
|
||||||
|
|
||||||
|
#[get("/images/<image>")]
|
||||||
|
pub async fn get_image(
|
||||||
|
image: String,
|
||||||
|
mut db: Connection<Db>,
|
||||||
|
) -> Result<NamedFile, status::Custom<&'static str>> {
|
||||||
|
let mut split = image.split('.').collect::<Vec<&str>>();
|
||||||
|
let format = split.pop().unwrap();
|
||||||
|
let image = split.join(".");
|
||||||
|
|
||||||
|
match Image::get_by_uuid(&mut db, &image).await {
|
||||||
|
Ok(_) => match Reader::open(format!("/srv/images/{image}.png")) {
|
||||||
|
Ok(i) => match i.decode() {
|
||||||
|
Ok(img) => {
|
||||||
|
let encoder = match format {
|
||||||
|
"jpg" => image::ImageFormat::Jpeg,
|
||||||
|
"jpeg" => image::ImageFormat::Jpeg,
|
||||||
|
"png" => image::ImageFormat::Png,
|
||||||
|
_ => {
|
||||||
|
panic!("invalid format")
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
img.save_with_format(format!("/tmp/{image}.{format}"), encoder)
|
||||||
|
.unwrap();
|
||||||
|
let file = NamedFile::open(Path::new(&format!("/tmp/{image}.{format}")))
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
fs::remove_file(format!("/tmp/{image}.{format}")).unwrap_or(());
|
||||||
|
|
||||||
|
Ok(file)
|
||||||
|
}
|
||||||
|
Err(why) => Err(match &why.to_string()[..] {
|
||||||
|
"Format error decoding Png: Invalid PNG signature." => {
|
||||||
|
status::Custom(Status::NotAcceptable, "That file isn't an image.")
|
||||||
|
}
|
||||||
|
_ => status::Custom(Status::InternalServerError, "Unknown decoding error"),
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
Err(_) => Err(status::Custom(
|
||||||
|
Status::InternalServerError,
|
||||||
|
"Unknown decoding error",
|
||||||
|
)),
|
||||||
|
},
|
||||||
|
Err(_) => Err(status::Custom(
|
||||||
|
Status::InternalServerError,
|
||||||
|
"File not found",
|
||||||
|
)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[post("/upload", format = "image/png", data = "<file>")]
|
||||||
|
pub async fn upload(
|
||||||
|
mut file: TempFile<'_>,
|
||||||
|
cookies: &CookieJar<'_>,
|
||||||
|
mut db: Connection<Db>,
|
||||||
|
) -> status::Custom<String> {
|
||||||
|
let uuid = Uuid::new_v4().to_string();
|
||||||
|
|
||||||
|
// login & perms check
|
||||||
|
match User::login_status(&mut db, cookies).await {
|
||||||
|
LoginStatus::LoggedIn(user) => {
|
||||||
|
match user.make_posts || user.admin {
|
||||||
|
// image validation check
|
||||||
|
true => {
|
||||||
|
match file.copy_to(format!("/srv/tmpimages/{uuid}.png")).await {
|
||||||
|
Ok(_) => {
|
||||||
|
// validate that it is, in fact, an image
|
||||||
|
match Reader::open(format!("/srv/tmpimages/{uuid}.png")) {
|
||||||
|
Ok(_) => {
|
||||||
|
match file.copy_to(format!("/srv/images/{uuid}.png")).await {
|
||||||
|
Ok(_) => match Image::create(&mut db, &uuid, user).await {
|
||||||
|
Ok(_) => {
|
||||||
|
match fs::remove_file(format!(
|
||||||
|
"/srv/tmpimages/{uuid}.png"
|
||||||
|
)) {
|
||||||
|
Ok(_) => status::Custom(Status::Created, uuid),
|
||||||
|
Err(why) => {
|
||||||
|
eprintln!("couldn't clear image from tmpimages: {why:?}");
|
||||||
|
status::Custom(Status::Ok, uuid)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(why) => {
|
||||||
|
eprintln!("{why:?}");
|
||||||
|
status::Custom(
|
||||||
|
Status::InternalServerError,
|
||||||
|
"Couldn't save to DB".to_string(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
Err(_) => status::Custom(
|
||||||
|
Status::InternalServerError,
|
||||||
|
"Couldn't copy file to final location".to_string(),
|
||||||
|
),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(_) => status::Custom(
|
||||||
|
Status::Forbidden,
|
||||||
|
"File isn't an image".to_string(),
|
||||||
|
),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(_) => status::Custom(
|
||||||
|
Status::InternalServerError,
|
||||||
|
"Couldn't save temporary file".to_string(),
|
||||||
|
),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
false => status::Custom(
|
||||||
|
Status::Unauthorized,
|
||||||
|
"You don't have the right permissions for that".to_string(),
|
||||||
|
),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
LoginStatus::InvalidToken => {
|
||||||
|
status::Custom(Status::Unauthorized, "Invalid login token".to_string())
|
||||||
|
}
|
||||||
|
LoginStatus::NotLoggedIn => {
|
||||||
|
status::Custom(Status::Unauthorized, "Not logged in".to_string())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[delete("/images/<uuid>")]
|
||||||
|
pub async fn delete_image(
|
||||||
|
mut db: Connection<Db>,
|
||||||
|
cookies: &CookieJar<'_>,
|
||||||
|
uuid: String,
|
||||||
|
) -> status::Custom<&'static str> {
|
||||||
|
match User::login_status(&mut db, cookies).await {
|
||||||
|
LoginStatus::LoggedIn(user) => {
|
||||||
|
match Image::is_owned_by(&mut db, &uuid, &user.username).await {
|
||||||
|
Ok(b) => match b {
|
||||||
|
// yeah this is jank but fuck types i don't want to figure that out
|
||||||
|
true => delimg(&mut db, uuid).await,
|
||||||
|
false => match user.admin {
|
||||||
|
true => delimg(&mut db, uuid).await,
|
||||||
|
false => status::Custom(Status::Unauthorized, "You don't own that image"),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
Err(_) => status::Custom(Status::NotFound, "Couldn't get image"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
LoginStatus::InvalidToken => status::Custom(Status::Unauthorized, "Invalid login token"),
|
||||||
|
LoginStatus::NotLoggedIn => status::Custom(Status::Unauthorized, "Not logged in"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn delimg(db: &mut Connection<Db>, uuid: String) -> status::Custom<&'static str> {
|
||||||
|
match Image::delete(db, &uuid).await {
|
||||||
|
Ok(_) => match fs::remove_file(format!("/srv/images/{uuid}.png")) {
|
||||||
|
Ok(_) => status::Custom(Status::Ok, "Image deleted"),
|
||||||
|
Err(why) => {
|
||||||
|
eprintln!("{why:?}");
|
||||||
|
status::Custom(
|
||||||
|
Status::ImATeapot,
|
||||||
|
"Image deleted from database but not filesystem",
|
||||||
|
)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
Err(_) => status::Custom(Status::InternalServerError, "Couldn't delete the image"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[get("/images/by-user/<username>")]
|
||||||
|
pub async fn get_images_by_username(
|
||||||
|
mut db: Connection<Db>,
|
||||||
|
cookies: &CookieJar<'_>,
|
||||||
|
username: String,
|
||||||
|
) -> Result<Json<Vec<String>>, String> {
|
||||||
|
let token = cookies.get_private("token");
|
||||||
|
match token {
|
||||||
|
Some(t) => match User::get_by_token(&mut db, t).await {
|
||||||
|
Some(user) => match user.admin || user.username == username {
|
||||||
|
true => match Image::get_by_username(&mut db, &username).await {
|
||||||
|
Ok(images) => Ok(Json::from(
|
||||||
|
images.into_iter().map(|i| i.uuid).collect::<Vec<String>>(),
|
||||||
|
)),
|
||||||
|
Err(why) => {
|
||||||
|
eprintln!("{why:?}");
|
||||||
|
Err("Couldn't get that user's images".to_string())
|
||||||
|
}
|
||||||
|
},
|
||||||
|
false => Err("You don't have permission to do this".to_string()),
|
||||||
|
},
|
||||||
|
None => Err("Invalid login token".to_string()),
|
||||||
|
},
|
||||||
|
None => Err("Not logged in".to_string()),
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,3 @@
|
||||||
|
pub mod images;
|
||||||
|
pub mod users;
|
||||||
|
pub mod web;
|
|
@ -0,0 +1,303 @@
|
||||||
|
use rocket::http::Status;
|
||||||
|
use rocket::response::content::RawHtml;
|
||||||
|
use rocket::response::status;
|
||||||
|
use rocket::serde::Serialize;
|
||||||
|
use rocket_db_pools::Connection;
|
||||||
|
use std::fs;
|
||||||
|
|
||||||
|
use rocket::http::CookieJar;
|
||||||
|
use rocket::serde::{json::Json, Deserialize};
|
||||||
|
|
||||||
|
use crate::tables::{Db, User};
|
||||||
|
use rocket::{get, post};
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
#[serde(crate = "rocket::serde")]
|
||||||
|
pub struct LoginInfo {
|
||||||
|
pub username: String,
|
||||||
|
pub password: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[post("/createuser", data = "<info>")]
|
||||||
|
pub async fn createuser(
|
||||||
|
mut db: Connection<Db>,
|
||||||
|
info: Json<LoginInfo>,
|
||||||
|
cookies: &CookieJar<'_>,
|
||||||
|
) -> status::Custom<String> {
|
||||||
|
let token = cookies.get_private("token");
|
||||||
|
match token.is_some() {
|
||||||
|
true => status::Custom(
|
||||||
|
Status::Forbidden,
|
||||||
|
"You're already logged in. Log out before trying to create a new account.".to_string(),
|
||||||
|
),
|
||||||
|
false => match User::get_by_username(&mut db, &info.username).await {
|
||||||
|
Some(_) => status::Custom(
|
||||||
|
Status::Forbidden,
|
||||||
|
"Username already taken. Please try again.".to_string(),
|
||||||
|
),
|
||||||
|
None => match User::create(&mut db, &info.username, &info.password).await {
|
||||||
|
Ok(_) => match User::get_by_username(&mut db, &info.username).await {
|
||||||
|
Some(user) => match user.set_new_token(&mut db).await {
|
||||||
|
Ok(t) => {
|
||||||
|
cookies.add_private(("token", t));
|
||||||
|
status::Custom(Status::Ok, "Your account has been created and you've been automatically logged in.".to_string())
|
||||||
|
}
|
||||||
|
Err(why) => {
|
||||||
|
eprintln!("{why:?}");
|
||||||
|
status::Custom(
|
||||||
|
Status::Created,
|
||||||
|
"Couldn't log you in. Your account has been created, though."
|
||||||
|
.to_string(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
None => status::Custom(
|
||||||
|
Status::InternalServerError,
|
||||||
|
"Something went really wrong. I don't know what.".to_string(),
|
||||||
|
),
|
||||||
|
},
|
||||||
|
Err(why) => {
|
||||||
|
format!("Couldn't create user: {}", why);
|
||||||
|
status::Custom(Status::InternalServerError, format!("{why}"))
|
||||||
|
}
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize)]
|
||||||
|
#[serde(crate = "rocket::serde")]
|
||||||
|
pub struct GetUser {
|
||||||
|
username: String,
|
||||||
|
admin: bool,
|
||||||
|
make_posts: bool,
|
||||||
|
comment: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[get("/account")]
|
||||||
|
pub async fn account(
|
||||||
|
mut db: Connection<Db>,
|
||||||
|
cookies: &CookieJar<'_>,
|
||||||
|
) -> status::Custom<Result<Json<GetUser>, &'static str>> {
|
||||||
|
let token = cookies.get_private("token");
|
||||||
|
match token {
|
||||||
|
Some(t) => match User::get_by_token(&mut db, t).await {
|
||||||
|
Some(user) => status::Custom(
|
||||||
|
Status::Ok,
|
||||||
|
Ok(Json(GetUser {
|
||||||
|
username: user.username,
|
||||||
|
admin: user.admin,
|
||||||
|
make_posts: user.make_posts,
|
||||||
|
comment: user.comment,
|
||||||
|
})),
|
||||||
|
),
|
||||||
|
None => status::Custom(Status::NotFound, Err("User doesn't exist.")),
|
||||||
|
},
|
||||||
|
None => status::Custom(Status::Unauthorized, Err("Not logged in")),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[post("/login", data = "<info>")]
|
||||||
|
pub async fn login(
|
||||||
|
mut db: Connection<Db>,
|
||||||
|
info: Json<LoginInfo>,
|
||||||
|
cookies: &CookieJar<'_>,
|
||||||
|
) -> status::Custom<&'static str> {
|
||||||
|
let token = cookies.get_private("token");
|
||||||
|
match token {
|
||||||
|
Some(_) => {
|
||||||
|
status::Custom(Status::Continue, "already logged in")
|
||||||
|
}
|
||||||
|
None => {
|
||||||
|
match User::get_by_username(&mut db, &info.username).await {
|
||||||
|
Some(user) => {
|
||||||
|
if user.password == sha256::digest(&info.password) {
|
||||||
|
match user.token {
|
||||||
|
Some(t) => {cookies.add_private(("token", t)); status::Custom(Status::Ok, "Logged in")},
|
||||||
|
None => {
|
||||||
|
match user.set_new_token(&mut db).await {
|
||||||
|
Ok(t) => {
|
||||||
|
cookies.add_private(("token", t));
|
||||||
|
status::Custom(Status::Ok, "Logged in")
|
||||||
|
},
|
||||||
|
Err(why) => {
|
||||||
|
eprintln!("{why:?}");
|
||||||
|
status::Custom(Status::InternalServerError, "Couldn't generate a token for you, therefore you weren't logged in.")
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
status::Custom(Status::Forbidden, "Invalid username or password (to those whining about why it doesn't tell you if the username or password is incorrect, security)")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None =>
|
||||||
|
status::Custom(Status::Forbidden, "Invalid username or password (to those whining about why it doesn't tell you if the username or password is incorrect, security)")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[post("/logout")]
|
||||||
|
pub async fn logout(cookies: &CookieJar<'_>) -> status::Custom<&'static str> {
|
||||||
|
match cookies.get_private("token") {
|
||||||
|
Some(_) => {
|
||||||
|
cookies.remove_private("token");
|
||||||
|
status::Custom(Status::Ok, "Logged out.")
|
||||||
|
}
|
||||||
|
None => status::Custom(Status::Unauthorized, "Not logged in."),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[get("/adminpanel")]
|
||||||
|
pub async fn adminpanel(
|
||||||
|
mut db: Connection<Db>,
|
||||||
|
cookies: &CookieJar<'_>,
|
||||||
|
) -> status::Custom<RawHtml<String>> {
|
||||||
|
let token = cookies.get_private("token");
|
||||||
|
match token {
|
||||||
|
Some(t) => match User::get_by_token(&mut db, t).await {
|
||||||
|
Some(user) => match user.admin {
|
||||||
|
true => status::Custom(
|
||||||
|
Status::Ok,
|
||||||
|
RawHtml(
|
||||||
|
fs::read_to_string("/srv/web/adminpanel.html")
|
||||||
|
.unwrap()
|
||||||
|
.replace("{{username}}", &user.username[..]),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
false => status::Custom(
|
||||||
|
Status::Unauthorized,
|
||||||
|
RawHtml(fs::read_to_string("/srv/web/invalidperms.html").unwrap()),
|
||||||
|
),
|
||||||
|
},
|
||||||
|
None => status::Custom(
|
||||||
|
Status::Unauthorized,
|
||||||
|
RawHtml(
|
||||||
|
fs::read_to_string("/srv/web/error.html")
|
||||||
|
.unwrap()
|
||||||
|
.replace("{{errorcode}}", "401"),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
},
|
||||||
|
None => status::Custom(
|
||||||
|
Status::Unauthorized,
|
||||||
|
RawHtml(fs::read_to_string("/srv/web/invalidperms.html").unwrap()),
|
||||||
|
),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize, Serialize)]
|
||||||
|
#[serde(crate = "rocket::serde")]
|
||||||
|
pub struct Perms {
|
||||||
|
admin: bool,
|
||||||
|
make_posts: bool,
|
||||||
|
comment: bool,
|
||||||
|
}
|
||||||
|
#[get("/perms/<username>")]
|
||||||
|
pub async fn api_perms(
|
||||||
|
mut db: Connection<Db>,
|
||||||
|
username: String,
|
||||||
|
cookies: &CookieJar<'_>,
|
||||||
|
) -> status::Custom<Json<Result<Perms, &'static str>>> {
|
||||||
|
match cookies.get_private("token") {
|
||||||
|
Some(t) => match User::get_by_token(&mut db, t).await {
|
||||||
|
Some(user) => match user.admin {
|
||||||
|
true => match User::get_by_username(&mut db, &username).await {
|
||||||
|
Some(user) => status::Custom(
|
||||||
|
Status::Ok,
|
||||||
|
Json(Ok(Perms {
|
||||||
|
admin: user.admin,
|
||||||
|
make_posts: user.make_posts,
|
||||||
|
comment: user.comment,
|
||||||
|
})),
|
||||||
|
),
|
||||||
|
None => status::Custom(Status::NotFound, Json(Err("User doesn't exist"))),
|
||||||
|
},
|
||||||
|
false => status::Custom(
|
||||||
|
Status::Unauthorized,
|
||||||
|
Json(Err("You don't have the permission to do this")),
|
||||||
|
),
|
||||||
|
},
|
||||||
|
None => status::Custom(Status::Unauthorized, Json(Err("Invalid token"))),
|
||||||
|
},
|
||||||
|
None => status::Custom(Status::Unauthorized, Json(Err("Not logged in"))),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
#[serde(crate = "rocket::serde")]
|
||||||
|
pub struct TogglePerms {
|
||||||
|
perm: String,
|
||||||
|
value: bool,
|
||||||
|
username: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[post("/toggleperms", data = "<info>")]
|
||||||
|
pub async fn toggleperms(
|
||||||
|
mut db: Connection<Db>,
|
||||||
|
info: Json<TogglePerms>,
|
||||||
|
cookies: &CookieJar<'_>,
|
||||||
|
) -> status::Custom<String> {
|
||||||
|
match cookies.get_private("token") {
|
||||||
|
Some(t) => {
|
||||||
|
match User::get_by_token(&mut db, t).await {
|
||||||
|
Some(user) => {
|
||||||
|
match user.admin {
|
||||||
|
true => match User::get_by_username(&mut db, &info.username).await {
|
||||||
|
Some(toggled_user) => {
|
||||||
|
match toggled_user.username == user.username && info.perm == "admin"
|
||||||
|
{
|
||||||
|
true => status::Custom(
|
||||||
|
Status::Forbidden,
|
||||||
|
"You can't change your own admin status".to_string(),
|
||||||
|
),
|
||||||
|
false => {
|
||||||
|
let admin_username = std::env::var("ADMIN_USERNAME")
|
||||||
|
.expect("set ADMIN_USERNAME env var");
|
||||||
|
match toggled_user.username == admin_username {
|
||||||
|
true => status::Custom(
|
||||||
|
Status::Forbidden,
|
||||||
|
"You can't change the system admin's perms."
|
||||||
|
.to_string(),
|
||||||
|
),
|
||||||
|
false => {
|
||||||
|
match info.perm == "admin"
|
||||||
|
&& user.username != admin_username
|
||||||
|
{
|
||||||
|
true => status::Custom(
|
||||||
|
Status::Forbidden,
|
||||||
|
"You can't change other people's admin status."
|
||||||
|
.to_string(),
|
||||||
|
),
|
||||||
|
false => {
|
||||||
|
match toggled_user.set_role(&mut db,&info.perm,&info.value).await {
|
||||||
|
Ok(_) => status::Custom(Status::Ok, "Done".to_string()),
|
||||||
|
Err(why) => status::Custom(Status::InternalServerError, format!(
|
||||||
|
"Couldn't update the user's role: {why}"
|
||||||
|
)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None => status::Custom(
|
||||||
|
Status::NotFound,
|
||||||
|
"The user you're trying to toggle perms for doesn't exist."
|
||||||
|
.to_string(),
|
||||||
|
),
|
||||||
|
},
|
||||||
|
false => {
|
||||||
|
status::Custom(Status::Unauthorized, "You aren't an admin.".to_string())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None => status::Custom(Status::Unauthorized, "Invalid login token".to_string()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None => status::Custom(Status::Unauthorized, "Not logged in".to_string()),
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,22 @@
|
||||||
|
use rocket::{get, response::content::RawHtml};
|
||||||
|
use std::fs;
|
||||||
|
|
||||||
|
#[get("/login")]
|
||||||
|
pub fn login_page() -> RawHtml<String> {
|
||||||
|
RawHtml(fs::read_to_string("/srv/web/login.html").unwrap())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[get("/createuser")]
|
||||||
|
pub fn createuser_page() -> RawHtml<String> {
|
||||||
|
RawHtml(fs::read_to_string("/srv/web/createuser.html").unwrap())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[get("/uploadimage")]
|
||||||
|
pub fn uploadimage() -> RawHtml<String> {
|
||||||
|
RawHtml(fs::read_to_string("/srv/web/uploadimage.html").unwrap())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[get("/myimages")]
|
||||||
|
pub fn myimages() -> RawHtml<String> {
|
||||||
|
RawHtml(fs::read_to_string("/srv/web/myimages.html").unwrap())
|
||||||
|
}
|
295
src/tables.rs
295
src/tables.rs
|
@ -17,23 +17,34 @@ pub struct Db(PgPool);
|
||||||
#[derive(FromRow)]
|
#[derive(FromRow)]
|
||||||
pub struct Post {
|
pub struct Post {
|
||||||
pub id: i32,
|
pub id: i32,
|
||||||
|
pub uuid: String,
|
||||||
|
pub text_id: String,
|
||||||
pub title: String,
|
pub title: String,
|
||||||
pub body: String,
|
pub body: String,
|
||||||
pub published: bool,
|
pub published: bool,
|
||||||
}
|
}
|
||||||
impl Post {
|
impl Post {
|
||||||
pub async fn create(mut db: Connection<Db>, title: String, body: String, published: bool) {
|
pub async fn create(
|
||||||
|
mut db: Connection<Db>,
|
||||||
|
title: String, /*ex: Why Trans People Deserve All Your Money*/
|
||||||
|
body: String, /*ex: # Because we're cooler than you */
|
||||||
|
published: bool,
|
||||||
|
uuid: String,
|
||||||
|
text_id: String, /*ex: why-trans-people-deserve-all-your-money */
|
||||||
|
) {
|
||||||
match db
|
match db
|
||||||
.fetch_all(
|
.fetch_all(
|
||||||
sqlx::query(
|
sqlx::query(
|
||||||
r#"
|
r#"
|
||||||
INSERT INTO posts (title, body, published)
|
INSERT INTO posts (title, body, published, uuid, text_id)
|
||||||
VALUES ($1, $2, $3);
|
VALUES ($1, $2, $3, $4, $5);
|
||||||
"#,
|
"#,
|
||||||
)
|
)
|
||||||
.bind(title)
|
.bind(title)
|
||||||
.bind(body)
|
.bind(body)
|
||||||
.bind(published),
|
.bind(published)
|
||||||
|
.bind(uuid)
|
||||||
|
.bind(text_id),
|
||||||
)
|
)
|
||||||
.await
|
.await
|
||||||
{
|
{
|
||||||
|
@ -50,12 +61,204 @@ impl Post {
|
||||||
.unwrap();
|
.unwrap();
|
||||||
Post {
|
Post {
|
||||||
id: res.get::<i32, _>("id"),
|
id: res.get::<i32, _>("id"),
|
||||||
|
uuid: res.get::<String, _>("uuid"),
|
||||||
|
text_id: res.get::<String, _>("text_id"),
|
||||||
title: res.get::<String, _>("title"),
|
title: res.get::<String, _>("title"),
|
||||||
body: res.get::<String, _>("body"),
|
body: res.get::<String, _>("body"),
|
||||||
published: res.get::<bool, _>("published"),
|
published: res.get::<bool, _>("published"),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
pub async fn get_by_uuid(mut db: Connection<Db>, uuid: String) -> Post {
|
||||||
|
let res = db
|
||||||
|
.fetch_one(sqlx::query("SELECT * FROM posts WHERE uuid = $1;").bind(uuid))
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
Post {
|
||||||
|
id: res.get::<i32, _>("id"),
|
||||||
|
uuid: res.get::<String, _>("uuid"),
|
||||||
|
text_id: res.get::<String, _>("text_id"),
|
||||||
|
title: res.get::<String, _>("title"),
|
||||||
|
body: res.get::<String, _>("body"),
|
||||||
|
published: res.get::<bool, _>("published"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pub async fn get_by_text_id(mut db: Connection<Db>, text_id: String) -> Post {
|
||||||
|
let res = db
|
||||||
|
.fetch_one(sqlx::query("SELECT * FROM posts WHERE text_id = $1;").bind(text_id))
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
Post {
|
||||||
|
id: res.get::<i32, _>("id"),
|
||||||
|
uuid: res.get::<String, _>("uuid"),
|
||||||
|
text_id: res.get::<String, _>("text_id"),
|
||||||
|
title: res.get::<String, _>("title"),
|
||||||
|
body: res.get::<String, _>("body"),
|
||||||
|
published: res.get::<bool, _>("published"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn edit_body(
|
||||||
|
mut db: Connection<Db>,
|
||||||
|
id: i32,
|
||||||
|
new_body: String,
|
||||||
|
) -> Result<(), String> {
|
||||||
|
match db
|
||||||
|
.execute(
|
||||||
|
sqlx::query("UPDATE posts SET body = $1 WHERE id = $2;")
|
||||||
|
.bind(new_body)
|
||||||
|
.bind(id),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
Ok(_) => Ok(()),
|
||||||
|
Err(why) => {
|
||||||
|
eprintln!("{why:?}");
|
||||||
|
Err("Couldn't update post".to_string())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pub async fn edit_body_by_uuid(
|
||||||
|
mut db: Connection<Db>,
|
||||||
|
uuid: String,
|
||||||
|
new_body: String,
|
||||||
|
) -> Result<(), String> {
|
||||||
|
match db
|
||||||
|
.execute(
|
||||||
|
sqlx::query("UPDATE posts SET body = $1 WHERE uuid = $2;")
|
||||||
|
.bind(new_body)
|
||||||
|
.bind(uuid),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
Ok(_) => Ok(()),
|
||||||
|
Err(why) => {
|
||||||
|
eprintln!("{why:?}");
|
||||||
|
Err("Couldn't update post".to_string())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pub async fn edit_body_by_text_id(
|
||||||
|
mut db: Connection<Db>,
|
||||||
|
text_id: String,
|
||||||
|
new_body: String,
|
||||||
|
) -> Result<(), String> {
|
||||||
|
match db
|
||||||
|
.execute(
|
||||||
|
sqlx::query("UPDATE posts SET body = $1 WHERE text_id = $2;")
|
||||||
|
.bind(new_body)
|
||||||
|
.bind(text_id),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
Ok(_) => Ok(()),
|
||||||
|
Err(why) => {
|
||||||
|
eprintln!("{why:?}");
|
||||||
|
Err("Couldn't update post".to_string())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pub async fn edit_title(
|
||||||
|
mut db: Connection<Db>,
|
||||||
|
id: i32,
|
||||||
|
new_title: String,
|
||||||
|
) -> Result<(), String> {
|
||||||
|
match db
|
||||||
|
.execute(
|
||||||
|
sqlx::query("UPDATE posts SET title = $1 WHERE id = $2;")
|
||||||
|
.bind(new_title)
|
||||||
|
.bind(id),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
Ok(_) => Ok(()),
|
||||||
|
Err(why) => {
|
||||||
|
eprintln!("{why:?}");
|
||||||
|
Err("Couldn't update post".to_string())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pub async fn edit_title_by_uuid(
|
||||||
|
mut db: Connection<Db>,
|
||||||
|
uuid: String,
|
||||||
|
new_title: String,
|
||||||
|
) -> Result<(), String> {
|
||||||
|
match db
|
||||||
|
.execute(
|
||||||
|
sqlx::query("UPDATE posts SET title = $1 WHERE uuid = $2;")
|
||||||
|
.bind(new_title)
|
||||||
|
.bind(uuid),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
Ok(_) => Ok(()),
|
||||||
|
Err(why) => {
|
||||||
|
eprintln!("{why:?}");
|
||||||
|
Err("Couldn't update post".to_string())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pub async fn edit_title_by_text_id(
|
||||||
|
mut db: Connection<Db>,
|
||||||
|
text_id: String,
|
||||||
|
new_title: String,
|
||||||
|
) -> Result<(), String> {
|
||||||
|
match db
|
||||||
|
.execute(
|
||||||
|
sqlx::query("UPDATE posts SET body = $1 WHERE text_id = $2;")
|
||||||
|
.bind(new_title)
|
||||||
|
.bind(text_id),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
Ok(_) => Ok(()),
|
||||||
|
Err(why) => {
|
||||||
|
eprintln!("{why:?}");
|
||||||
|
Err("Couldn't update post".to_string())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pub async fn edit_text_id(
|
||||||
|
mut db: Connection<Db>,
|
||||||
|
id: i32,
|
||||||
|
new_text_id: String,
|
||||||
|
) -> Result<(), String> {
|
||||||
|
match db
|
||||||
|
.execute(
|
||||||
|
sqlx::query("UPDATE posts SET text_id = $1 WHERE id = $2;")
|
||||||
|
.bind(new_text_id)
|
||||||
|
.bind(id),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
Ok(_) => Ok(()),
|
||||||
|
Err(why) => {
|
||||||
|
eprintln!("{why:?}");
|
||||||
|
Err("Couldn't update post".to_string())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pub async fn edit_text_id_by_uuid(
|
||||||
|
mut db: Connection<Db>,
|
||||||
|
uuid: String,
|
||||||
|
new_text_id: String,
|
||||||
|
) -> Result<(), String> {
|
||||||
|
match db
|
||||||
|
.execute(
|
||||||
|
sqlx::query("UPDATE posts SET text_id = $1 WHERE uuid = $2;")
|
||||||
|
.bind(new_text_id)
|
||||||
|
.bind(uuid),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
Ok(_) => Ok(()),
|
||||||
|
Err(why) => {
|
||||||
|
eprintln!("{why:?}");
|
||||||
|
Err("Couldn't update post".to_string())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(FromRow, Debug)]
|
#[derive(FromRow, Debug)]
|
||||||
pub struct User {
|
pub struct User {
|
||||||
pub id: i32,
|
pub id: i32,
|
||||||
|
@ -70,15 +273,19 @@ pub struct User {
|
||||||
pub enum LoginStatus {
|
pub enum LoginStatus {
|
||||||
InvalidToken,
|
InvalidToken,
|
||||||
NotLoggedIn,
|
NotLoggedIn,
|
||||||
LoggedIn(User)
|
LoggedIn(User),
|
||||||
}
|
}
|
||||||
|
|
||||||
impl User {
|
impl User {
|
||||||
pub async fn create(db: &mut Connection<Db>, username: &String, password: &String) -> Result<String, String> {
|
pub async fn create(
|
||||||
|
db: &mut Connection<Db>,
|
||||||
|
username: &String,
|
||||||
|
password: &String,
|
||||||
|
) -> Result<String, String> {
|
||||||
match Regex::new(r"[^A-Za-z0-9_]") {
|
match Regex::new(r"[^A-Za-z0-9_]") {
|
||||||
Ok(r) => {
|
Ok(r) => {
|
||||||
match r.captures(username) {
|
match r.captures(username) {
|
||||||
Some(_) =>
|
Some(_) =>
|
||||||
Err("The username contains invalid characters. Only letters, numbers, and underscores are allowed.".to_string())
|
Err("The username contains invalid characters. Only letters, numbers, and underscores are allowed.".to_string())
|
||||||
,
|
,
|
||||||
None => {
|
None => {
|
||||||
|
@ -98,7 +305,7 @@ impl User {
|
||||||
.bind(sha256::digest(password)),
|
.bind(sha256::digest(password)),
|
||||||
).await
|
).await
|
||||||
{
|
{
|
||||||
Ok(_) =>
|
Ok(_) =>
|
||||||
Ok("Created user.".to_string())
|
Ok("Created user.".to_string())
|
||||||
,
|
,
|
||||||
Err(why) => {
|
Err(why) => {
|
||||||
|
@ -112,7 +319,7 @@ impl User {
|
||||||
}
|
}
|
||||||
Err(why) => {
|
Err(why) => {
|
||||||
eprintln!("Couldn't compile name regex: {why:?}");
|
eprintln!("Couldn't compile name regex: {why:?}");
|
||||||
Err("Couldn't compile name regex.".to_string())
|
Err("Couldn't compile name regex.".to_string())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -226,17 +433,11 @@ impl User {
|
||||||
|
|
||||||
pub async fn login_status(db: &mut Connection<Db>, cookies: &CookieJar<'_>) -> LoginStatus {
|
pub async fn login_status(db: &mut Connection<Db>, cookies: &CookieJar<'_>) -> LoginStatus {
|
||||||
match cookies.get_private("token") {
|
match cookies.get_private("token") {
|
||||||
Some(t) => {
|
Some(t) => match User::get_by_token(db, t).await {
|
||||||
match User::get_by_token(db, t).await {
|
Some(user) => LoginStatus::LoggedIn(user),
|
||||||
Some(user) => {
|
None => LoginStatus::InvalidToken,
|
||||||
LoginStatus::LoggedIn(user)
|
|
||||||
},
|
|
||||||
None => {
|
|
||||||
LoginStatus::InvalidToken
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
},
|
||||||
None => LoginStatus::NotLoggedIn
|
None => LoginStatus::NotLoggedIn,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -262,12 +463,10 @@ impl Image {
|
||||||
)
|
)
|
||||||
.await
|
.await
|
||||||
{
|
{
|
||||||
Ok(_) =>
|
Ok(_) => Ok(()),
|
||||||
Ok(())
|
|
||||||
,
|
|
||||||
Err(why) => {
|
Err(why) => {
|
||||||
eprintln!("Couldn't create database entry: {why:?}");
|
eprintln!("Couldn't create database entry: {why:?}");
|
||||||
Err("Couldn't create image.".to_string())
|
Err("Couldn't create image.".to_string())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -276,26 +475,31 @@ impl Image {
|
||||||
.fetch_one(sqlx::query("SELECT * FROM images WHERE uuid = $1;").bind(uuid))
|
.fetch_one(sqlx::query("SELECT * FROM images WHERE uuid = $1;").bind(uuid))
|
||||||
.await
|
.await
|
||||||
{
|
{
|
||||||
Ok(img) => Ok(Image {
|
Ok(img) => Ok(Image {
|
||||||
id: img.get::<i32, _>("id"),
|
id: img.get::<i32, _>("id"),
|
||||||
uuid: img.get::<String, _>("uuid"),
|
uuid: img.get::<String, _>("uuid"),
|
||||||
owner_name: img.get::<String, _>("owner_name"),
|
owner_name: img.get::<String, _>("owner_name"),
|
||||||
}),
|
}),
|
||||||
Err(_) => Err("Couldn't get image.".to_string()),
|
Err(_) => Err("Couldn't get image.".to_string()),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
pub async fn is_owned_by(db: &mut Connection<Db>, uuid: &String, username: &String) -> Result<bool, String> {
|
pub async fn is_owned_by(
|
||||||
|
db: &mut Connection<Db>,
|
||||||
|
uuid: &String,
|
||||||
|
username: &String,
|
||||||
|
) -> Result<bool, String> {
|
||||||
match Image::get_by_uuid(db, uuid).await {
|
match Image::get_by_uuid(db, uuid).await {
|
||||||
Ok(img) => {
|
Ok(img) => Ok(&img.owner_name == username),
|
||||||
Ok(&img.owner_name == username)
|
|
||||||
},
|
|
||||||
Err(why) => {
|
Err(why) => {
|
||||||
eprintln!("{why:?}");
|
eprintln!("{why:?}");
|
||||||
Err("couldn't get image".to_string())
|
Err("couldn't get image".to_string())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
pub async fn get_by_username(db: &mut Connection<Db>, owner_name: &String) -> Result<Vec<Image>, String> {
|
pub async fn get_by_username(
|
||||||
|
db: &mut Connection<Db>,
|
||||||
|
owner_name: &String,
|
||||||
|
) -> Result<Vec<Image>, String> {
|
||||||
match db
|
match db
|
||||||
.fetch_all(sqlx::query("SELECT * FROM images WHERE owner_name = $1;").bind(owner_name))
|
.fetch_all(sqlx::query("SELECT * FROM images WHERE owner_name = $1;").bind(owner_name))
|
||||||
.await
|
.await
|
||||||
|
@ -303,27 +507,30 @@ impl Image {
|
||||||
Ok(imgs) => {
|
Ok(imgs) => {
|
||||||
let mut res = vec![];
|
let mut res = vec![];
|
||||||
for img in imgs {
|
for img in imgs {
|
||||||
res.push(Image {
|
res.push(Image {
|
||||||
id: img.get::<i32, _>("id"),
|
id: img.get::<i32, _>("id"),
|
||||||
uuid: img.get::<String, _>("uuid"),
|
uuid: img.get::<String, _>("uuid"),
|
||||||
owner_name: img.get::<String, _>("owner_name"),
|
owner_name: img.get::<String, _>("owner_name"),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
Ok(res)
|
Ok(res)
|
||||||
},
|
}
|
||||||
Err(_) => Err("Couldn't get image.".to_string()),
|
Err(_) => Err("Couldn't get image.".to_string()),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
pub async fn delete(db: &mut Connection<Db>, uuid: &String) -> Result<(), ()> {
|
pub async fn delete(db: &mut Connection<Db>, uuid: &String) -> Result<(), ()> {
|
||||||
match db.execute(sqlx::query("DELETE FROM images WHERE uuid = $1").bind(uuid)).await {
|
match db
|
||||||
|
.execute(sqlx::query("DELETE FROM images WHERE uuid = $1").bind(uuid))
|
||||||
|
.await
|
||||||
|
{
|
||||||
Ok(rows_gone) => {
|
Ok(rows_gone) => {
|
||||||
eprintln!("Deleted {rows_gone:?} rows.");
|
eprintln!("Deleted {rows_gone:?} rows.");
|
||||||
Ok(())
|
Ok(())
|
||||||
},
|
}
|
||||||
Err(why) => {
|
Err(why) => {
|
||||||
eprintln!("Couldn't remove database entry: {why:?}");
|
eprintln!("Couldn't remove database entry: {why:?}");
|
||||||
Err(())
|
Err(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in New Issue