This commit is contained in:
StNicolay 2024-08-09 17:02:02 +03:00
parent 8eb5be96b3
commit 194210ec89
Signed by: StNicolay
GPG Key ID: 9693D04DCD962B0D
17 changed files with 58 additions and 63 deletions

View File

@ -1,6 +1,6 @@
{ {
"db_name": "PostgreSQL", "db_name": "PostgreSQL",
"query": "INSERT INTO folders(parent_folder_id, owner_id, folder_name) VALUES ($1, $2, $3) RETURNING folder_id", "query": "INSERT INTO folders(parent_folder_id, owner_id, folder_name)\nSELECT $1, owner_id, $2 FROM folders WHERE parent_folder_id = $1\nRETURNING folder_id",
"describe": { "describe": {
"columns": [ "columns": [
{ {
@ -12,7 +12,6 @@
"parameters": { "parameters": {
"Left": [ "Left": [
"Uuid", "Uuid",
"Int4",
"Varchar" "Varchar"
] ]
}, },
@ -20,5 +19,5 @@
false false
] ]
}, },
"hash": "3dd4a65d3106d742c2221c0589ac68d4621c6e351f9fbb7aa58629ff2d829234" "hash": "28910fe1287349babee7578fa647d031f4e3c94812d46e1c4afa73fa70059720"
} }

View File

@ -21,7 +21,7 @@
{ {
"ordinal": 3, "ordinal": 3,
"name": "created_at", "name": "created_at",
"type_info": "Timestamp" "type_info": "Timestamptz"
} }
], ],
"parameters": { "parameters": {

View File

@ -1,6 +1,6 @@
{ {
"db_name": "PostgreSQL", "db_name": "PostgreSQL",
"query": "SELECT\n user_id, username, email, \n GREATEST (\n similarity (email, $1),\n similarity (username, $1)\n ) as \"similarity!\"\nFROM\n users\nORDER BY\n \"similarity!\" DESC", "query": "SELECT\n user_id, username, email, \n GREATEST (\n similarity (email, $1),\n similarity (username, $1)\n ) as \"similarity!\"\nFROM\n users\nORDER BY\n \"similarity!\" DESC\nLIMIT 20",
"describe": { "describe": {
"columns": [ "columns": [
{ {
@ -36,5 +36,5 @@
null null
] ]
}, },
"hash": "8d8bf29e632723ba48a19ea52a8466424f7628e84df17178bf26eaca1cc99aca" "hash": "e0d415b13ccf7aa865558395eb6997bfff50762d36cf3742470a897f4588c802"
} }

View File

@ -26,12 +26,12 @@
{ {
"ordinal": 4, "ordinal": 4,
"name": "created_at", "name": "created_at",
"type_info": "Timestamp" "type_info": "Timestamptz"
}, },
{ {
"ordinal": 5, "ordinal": 5,
"name": "updated_at", "name": "updated_at",
"type_info": "Timestamp" "type_info": "Timestamptz"
} }
], ],
"parameters": { "parameters": {

View File

@ -21,7 +21,7 @@
{ {
"ordinal": 3, "ordinal": 3,
"name": "created_at", "name": "created_at",
"type_info": "Timestamp" "type_info": "Timestamptz"
} }
], ],
"parameters": { "parameters": {

35
Cargo.lock generated
View File

@ -321,9 +321,9 @@ checksum = "8318a53db07bb3f8dca91a600466bdb3f2eaadeedfdbcf02e1accbad9271ba50"
[[package]] [[package]]
name = "cc" name = "cc"
version = "1.1.7" version = "1.1.8"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "26a5c3fd7bfa1ce3897a3a3501d362b2d87b7f2583ebcb4a949ec25911025cbc" checksum = "504bdec147f2cc13c8b57ed9401fd8a147cc66b67ad5cb241394244f2c947549"
dependencies = [ dependencies = [
"jobserver", "jobserver",
"libc", "libc",
@ -920,9 +920,9 @@ dependencies = [
[[package]] [[package]]
name = "hyper-util" name = "hyper-util"
version = "0.1.6" version = "0.1.7"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3ab92f4f49ee4fb4f997c784b7a2e0fa70050211e0b6a287f898c3c9785ca956" checksum = "cde7055719c54e36e95e8719f95883f22072a48ede39db7fc17a4e1d5281e9b9"
dependencies = [ dependencies = [
"bytes", "bytes",
"futures-util", "futures-util",
@ -1259,9 +1259,9 @@ dependencies = [
[[package]] [[package]]
name = "object" name = "object"
version = "0.36.2" version = "0.36.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3f203fa8daa7bb185f760ae12bd8e097f63d17041dcdcaf675ac54cdf863170e" checksum = "27b64972346851a39438c60b341ebc01bba47464ae329e55cf343eb93964efd9"
dependencies = [ dependencies = [
"memchr", "memchr",
] ]
@ -1731,18 +1731,18 @@ dependencies = [
[[package]] [[package]]
name = "serde" name = "serde"
version = "1.0.204" version = "1.0.205"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bc76f558e0cbb2a839d37354c575f1dc3fdc6546b5be373ba43d95f231bf7c12" checksum = "e33aedb1a7135da52b7c21791455563facbbcc43d0f0f66165b42c21b3dfb150"
dependencies = [ dependencies = [
"serde_derive", "serde_derive",
] ]
[[package]] [[package]]
name = "serde_derive" name = "serde_derive"
version = "1.0.204" version = "1.0.205"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e0cd7e117be63d3c3678776753929474f3b04a43a080c744d6b0ae2a8c28e222" checksum = "692d6f5ac90220161d6774db30c662202721e64aed9058d2c394f451261420c1"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
@ -2156,15 +2156,15 @@ checksum = "a7065abeca94b6a8a577f9bd45aa0867a2238b74e8eb67cf10d492bc39351394"
[[package]] [[package]]
name = "tempfile" name = "tempfile"
version = "3.11.0" version = "3.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b8fcd239983515c23a32fb82099f97d0b11b8c72f654ed659363a95c3dad7a53" checksum = "04cbcdd0c794ebb0d4cf35e88edd2f7d2c4c3e9a5a6dab322839b321c6a87a64"
dependencies = [ dependencies = [
"cfg-if", "cfg-if",
"fastrand", "fastrand",
"once_cell", "once_cell",
"rustix", "rustix",
"windows-sys 0.52.0", "windows-sys 0.59.0",
] ]
[[package]] [[package]]
@ -2653,6 +2653,15 @@ dependencies = [
"windows-targets 0.52.6", "windows-targets 0.52.6",
] ]
[[package]]
name = "windows-sys"
version = "0.59.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b"
dependencies = [
"windows-targets 0.52.6",
]
[[package]] [[package]]
name = "windows-targets" name = "windows-targets"
version = "0.48.5" version = "0.48.5"

View File

@ -8,3 +8,4 @@ FROM
users users
ORDER BY ORDER BY
"similarity!" DESC "similarity!" DESC
LIMIT 20

View File

@ -67,10 +67,11 @@ pub async fn get_permissions(
} }
pub async fn get_name(file_id: Uuid, pool: &Pool) -> sqlx::Result<Option<String>> { pub async fn get_name(file_id: Uuid, pool: &Pool) -> sqlx::Result<Option<String>> {
let record = sqlx::query!("SELECT file_name FROM files WHERE file_id = $1", file_id) let name = sqlx::query!("SELECT file_name FROM files WHERE file_id = $1", file_id)
.fetch_optional(pool) .fetch_optional(pool)
.await?; .await?
Ok(record.map(|record| record.file_name)) .map(|record| record.file_name);
Ok(name)
} }
pub async fn delete(file_id: Uuid, pool: &Pool) -> sqlx::Result<bool> { pub async fn delete(file_id: Uuid, pool: &Pool) -> sqlx::Result<bool> {

View File

@ -80,7 +80,7 @@ pub async fn get(user_id: i32, pool: &Pool) -> sqlx::Result<Option<UserInfo>> {
.await .await
} }
/// Gets the hashed password field by either the email or th username /// Gets the hashed password field by either the email or the username
pub async fn get_hash(search_string: &str, pool: &Pool) -> sqlx::Result<Option<(i32, Vec<u8>)>> { pub async fn get_hash(search_string: &str, pool: &Pool) -> sqlx::Result<Option<(i32, Vec<u8>)>> {
let record = sqlx::query!( let record = sqlx::query!(
"SELECT user_id, hashed_password FROM users WHERE username = $1 OR email = $1", "SELECT user_id, hashed_password FROM users WHERE username = $1 OR email = $1",

View File

@ -14,15 +14,9 @@ pub async fn delete(
.await .await
.can_write_guard()?; .can_write_guard()?;
let deleted = db::file::delete(params.file_id, &state.pool) db::file::delete(params.file_id, &state.pool)
.await .await
.handle_internal("Error deleting the file")?; .handle_internal("Error deleting the file")?;
if !deleted {
return Err(GeneralError::message(
StatusCode::NOT_FOUND,
"Item not found",
)); // Will not happen most of the time due to can write guard
}
state state
.storage .storage

View File

@ -1,3 +1,4 @@
use db::{file::FileWithoutParentId, folder::FolderWithoutParentId};
use tokio::try_join; use tokio::try_join;
use super::list::Params; use super::list::Params;
@ -6,13 +7,13 @@ use crate::prelude::*;
#[derive(Serialize, Debug)] #[derive(Serialize, Debug)]
pub struct FolderStructure { pub struct FolderStructure {
#[serde(flatten)] #[serde(flatten)]
folder_base: db::folder::FolderWithoutParentId, folder_base: FolderWithoutParentId,
folders: Vec<FolderStructure>, folders: Vec<FolderStructure>,
files: Vec<db::file::FileWithoutParentId>, files: Vec<FileWithoutParentId>,
} }
impl From<db::folder::FolderWithoutParentId> for FolderStructure { impl From<FolderWithoutParentId> for FolderStructure {
fn from(value: db::folder::FolderWithoutParentId) -> Self { fn from(value: FolderWithoutParentId) -> Self {
FolderStructure { FolderStructure {
folder_base: value, folder_base: value,
folders: Vec::new(), folders: Vec::new(),

View File

@ -18,7 +18,7 @@ pub async fn set(
if params.folder_id == root { if params.folder_id == root {
return Err(GeneralError::message( return Err(GeneralError::message(
StatusCode::BAD_REQUEST, StatusCode::BAD_REQUEST,
"Cannot delete the root folder", "Cannot set permissions for the root folder",
)); ));
} }
@ -33,7 +33,7 @@ pub async fn set(
if folder_info.owner_id == params.user_id { if folder_info.owner_id == params.user_id {
return Err(GeneralError::message( return Err(GeneralError::message(
StatusCode::BAD_REQUEST, StatusCode::BAD_REQUEST,
"Cannot set permissions of the folder owner", "Cannot set permissions of the folder's owner",
)); ));
} }

View File

@ -8,11 +8,11 @@ pub struct Params {
type Response = GeneralResult<Json<db::users::UserInfo>>; type Response = GeneralResult<Json<db::users::UserInfo>>;
pub async fn get(State(pool): State<Pool>, Query(params): Query<Params>) -> Response { pub async fn get(State(pool): State<Pool>, Query(params): Query<Params>) -> Response {
let info = db::users::get(params.user_id, &pool) db::users::get(params.user_id, &pool)
.await .await
.handle_internal("Error getting the user")? .handle_internal("Error getting the user")?
.handle(StatusCode::NOT_FOUND, "User not found")?; .handle(StatusCode::NOT_FOUND, "User not found")
Ok(Json(info)) .map(Json)
} }
pub async fn current(state: State<Pool>, claims: Claims) -> Response { pub async fn current(state: State<Pool>, claims: Claims) -> Response {

View File

@ -15,7 +15,7 @@ pub async fn put(
claims: Claims, claims: Claims,
Json(params): Json<Params>, Json(params): Json<Params>,
) -> GeneralResult<Json<db::users::UserInfo>> { ) -> GeneralResult<Json<db::users::UserInfo>> {
params.validate().handle_validation()?; params.validate()?;
db::users::update(claims.user_id, &params.username, &params.email, &pool) db::users::update(claims.user_id, &params.username, &params.email, &pool)
.await .await
.handle_internal("Error updating the user") .handle_internal("Error updating the user")

View File

@ -48,7 +48,7 @@ pub async fn register(
State(pool): State<Pool>, State(pool): State<Pool>,
Form(params): Form<Params>, Form(params): Form<Params>,
) -> GeneralResult<Json<Token>> { ) -> GeneralResult<Json<Token>> {
params.validate().handle_validation()?; params.validate()?;
let password = HashedBytes::hash_bytes(params.password.as_bytes()).as_bytes(); let password = HashedBytes::hash_bytes(params.password.as_bytes()).as_bytes();
let id = db::users::create_user(&params.username, &params.email, &password, &pool) let id = db::users::create_user(&params.username, &params.email, &password, &pool)

View File

@ -41,6 +41,12 @@ impl IntoResponse for GeneralError {
} }
} }
impl From<validator::ValidationErrors> for GeneralError {
fn from(value: validator::ValidationErrors) -> Self {
GeneralError::message(StatusCode::BAD_REQUEST, value.to_string())
}
}
pub type GeneralResult<T> = Result<T, GeneralError>; pub type GeneralResult<T> = Result<T, GeneralError>;
pub trait ErrorHandlingExt<T> pub trait ErrorHandlingExt<T>
@ -92,19 +98,6 @@ pub trait ItemNotFoundExt<T> {
impl<T> ItemNotFoundExt<T> for Option<T> { impl<T> ItemNotFoundExt<T> for Option<T> {
fn item_not_found(self) -> GeneralResult<T> { fn item_not_found(self) -> GeneralResult<T> {
self.ok_or(GeneralError::const_message( self.handle(StatusCode::NOT_FOUND, "Item not found")
StatusCode::NOT_FOUND,
"Item not found",
))
}
}
pub trait ValidationExt<T> {
fn handle_validation(self) -> GeneralResult<T>;
}
impl<T> ValidationExt<T> for Result<T, validator::ValidationErrors> {
fn handle_validation(self) -> GeneralResult<T> {
self.map_err(|err| GeneralError::message(StatusCode::BAD_REQUEST, err.to_string()))
} }
} }

View File

@ -1,10 +1,7 @@
pub(crate) use crate::{ pub(crate) use crate::{
auth::Claims, auth::Claims,
db::{self, permissions::PermissionExt as _}, db::{self, permissions::PermissionExt as _},
errors::{ errors::{ErrorHandlingExt as _, GeneralError, GeneralResult, ItemNotFoundExt as _},
ErrorHandlingExt as _, GeneralError, GeneralResult, ItemNotFoundExt as _,
ValidationExt as _,
},
AppState, Pool, AppState, Pool,
}; };
pub use axum::{ pub use axum::{