Skip to content

Commit

Permalink
feat: sanitized path while storing approved papers
Browse files Browse the repository at this point in the history
  • Loading branch information
harshkhandeparkar committed Nov 17, 2024
1 parent 6163d56 commit eb9f91f
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 3 deletions.
9 changes: 6 additions & 3 deletions backend/src/db/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use std::time::Duration;

use crate::{
env::EnvVars,
pathutils::PaperCategory,
pathutils::{PaperCategory, Paths},
qp::{self, AdminDashboardQP, Exam, Semester},
routing::{EditReq, FileDetails},
};
Expand Down Expand Up @@ -147,8 +147,11 @@ impl Database {
} else if approve_status {
env_vars.paths.get_slug(
&format!(
"{}_{}_{}_{}_{}_{}.pdf",
id, course_code, course_name, year, semester, exam
"{}.pdf",
Paths::sanitize_path(&format!(
"{}_{}_{}_{}_{}_{}",
id, course_code, course_name, year, semester, exam
))
),
PaperCategory::Approved,
)
Expand Down
15 changes: 15 additions & 0 deletions backend/src/pathutils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -174,4 +174,19 @@ impl Paths {
pub fn get_url_from_slug(&self, slug: &str) -> Result<String, color_eyre::eyre::Error> {
Ok(self.static_files_url.join(slug)?.as_str().to_string())
}

/// Removes any non-alphanumeric character and replaces whitespaces with `-`
/// Also replaces `/` with `-` and multiple spaces or hyphens will be replaced with a single one
pub fn sanitize_path(path: &str) -> String {
path.replace('/', "-") // Replace specific characters with a `-`
.replace('-', " ") // Convert any series of spaces and hyphens to just spaces
.split_whitespace() // Split at whitespaces to later replace all whitespaces with `-`
.map(|part| {
part.chars()
.filter(|&character| character.is_alphanumeric() || character == '-' || character == '_') // Remove any character that is not a `-` or alphanumeric
.collect::<String>()
})
.collect::<Vec<String>>()
.join("-") // Join the parts with `-`
}
}
2 changes: 2 additions & 0 deletions backend/src/routing/handlers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,8 @@ pub async fn edit(
let old_filepath = state.env_vars.paths.get_path_from_slug(&old_filelink);
let new_filepath = state.env_vars.paths.get_path_from_slug(&new_qp.filelink);

println!("{}, {}", new_filepath.to_string_lossy(), old_filepath.to_string_lossy());

if fs::copy(old_filepath, new_filepath).await.is_ok() {
// Commit the transaction
tx.commit().await?;
Expand Down

0 comments on commit eb9f91f

Please sign in to comment.