Skip to content

Commit

Permalink
Merge pull request #21 from DataM0del/refactor/move-duplicated-code
Browse files Browse the repository at this point in the history
refactor: move duplicated token functions to utils
  • Loading branch information
tranxuanthang authored Oct 18, 2024
2 parents dd7626c + 0853be2 commit 0f567bc
Show file tree
Hide file tree
Showing 3 changed files with 66 additions and 117 deletions.
59 changes: 1 addition & 58 deletions server/src/routes/flag_lyrics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,10 @@ use axum::{
Json,
};
use serde::Deserialize;
use moka::future::Cache;
use std::sync::Arc;
use crate::{errors::ApiError, repositories::track_repository, AppState};
use sha2::{Digest, Sha256};
use hex;
use axum_macros::debug_handler;
use crate::utils::is_valid_publish_token;

#[derive(Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
Expand Down Expand Up @@ -46,58 +44,3 @@ pub async fn route(
None => Err(ApiError::IncorrectPublishTokenError)
}
}

async fn is_valid_publish_token(publish_token: &str, challenge_cache: &Cache<String, String>) -> bool {
let publish_token_parts = publish_token.split(":").collect::<Vec<&str>>();

if publish_token_parts.len() != 2 {
return false;
}

let prefix = publish_token_parts[0];
let nonce = publish_token_parts[1];
let target = challenge_cache.get(&format!("challenge:{}", prefix)).await;

match target {
Some(target) => {
let result = verify_answer(prefix, &target, nonce);

if result {
challenge_cache.remove(&format!("challenge:{}", prefix)).await;
true
} else {
false
}
},
None => {
false
}
}
}

pub fn verify_answer(prefix: &str, target: &str, nonce: &str) -> bool {
let input = format!("{}{}", prefix, nonce);
let mut hasher = Sha256::new();
hasher.update(input);
let hashed_bytes = hasher.finalize();

let target_bytes = match hex::decode(target) {
Ok(bytes) => bytes,
Err(_) => return false,
};

if target_bytes.len() != hashed_bytes.len() {
return false;
}

for (hashed_byte, target_byte) in hashed_bytes.iter().zip(target_bytes.iter()) {
if hashed_byte > target_byte {
return false;
}
if hashed_byte < target_byte {
break;
}
}

true
}
65 changes: 6 additions & 59 deletions server/src/routes/publish_lyrics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,13 @@ use axum::{
};
use rusqlite::Connection;
use serde::Deserialize;
use moka::future::Cache;
use std::sync::Arc;
use crate::{errors::ApiError, repositories::{lyrics_repository, track_repository}, utils::strip_timestamp, AppState};
use sha2::{Digest, Sha256};
use hex;
use crate::{
errors::ApiError,
repositories::{lyrics_repository, track_repository},
utils::{strip_timestamp, is_valid_publish_token},
AppState
};
use axum_macros::debug_handler;
use regex::Regex;

Expand Down Expand Up @@ -112,58 +114,3 @@ fn publish_lyrics(payload: &PublishRequest, conn: &mut Connection) -> Result<()>

Ok(())
}

async fn is_valid_publish_token(publish_token: &str, challenge_cache: &Cache<String, String>) -> bool {
let publish_token_parts = publish_token.split(":").collect::<Vec<&str>>();

if publish_token_parts.len() != 2 {
return false;
}

let prefix = publish_token_parts[0];
let nonce = publish_token_parts[1];
let target = challenge_cache.get(&format!("challenge:{}", prefix)).await;

match target {
Some(target) => {
let result = verify_answer(prefix, &target, nonce);

if result {
challenge_cache.remove(&format!("challenge:{}", prefix)).await;
true
} else {
false
}
},
None => {
false
}
}
}

pub fn verify_answer(prefix: &str, target: &str, nonce: &str) -> bool {
let input = format!("{}{}", prefix, nonce);
let mut hasher = Sha256::new();
hasher.update(input);
let hashed_bytes = hasher.finalize();

let target_bytes = match hex::decode(target) {
Ok(bytes) => bytes,
Err(_) => return false,
};

if target_bytes.len() != hashed_bytes.len() {
return false;
}

for (hashed_byte, target_byte) in hashed_bytes.iter().zip(target_bytes.iter()) {
if hashed_byte > target_byte {
return false;
}
if hashed_byte < target_byte {
break;
}
}

true
}
59 changes: 59 additions & 0 deletions server/src/utils.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use moka::future::Cache;
use sha2::{Digest, Sha256};
use secular::lower_lay_string;
use regex::Regex;
use collapse::collapse;
Expand All @@ -22,3 +24,60 @@ pub fn strip_timestamp(synced_lyrics: &str) -> String {
let plain_lyrics = re.replace_all(synced_lyrics, "");
plain_lyrics.to_string()
}

// tokens

pub async fn is_valid_publish_token(publish_token: &str, challenge_cache: &Cache<String, String>) -> bool {
let publish_token_parts = publish_token.split(":").collect::<Vec<&str>>();

if publish_token_parts.len() != 2 {
return false;
}

let prefix = publish_token_parts[0];
let nonce = publish_token_parts[1];
let target = challenge_cache.get(&format!("challenge:{}", prefix)).await;

match target {
Some(target) => {
let result = verify_answer(prefix, &target, nonce);

if result {
challenge_cache.remove(&format!("challenge:{}", prefix)).await;
true
} else {
false
}
},
None => {
false
}
}
}

pub fn verify_answer(prefix: &str, target: &str, nonce: &str) -> bool {
let input = format!("{}{}", prefix, nonce);
let mut hasher = Sha256::new();
hasher.update(input);
let hashed_bytes = hasher.finalize();

let target_bytes = match hex::decode(target) {
Ok(bytes) => bytes,
Err(_) => return false,
};

if target_bytes.len() != hashed_bytes.len() {
return false;
}

for (hashed_byte, target_byte) in hashed_bytes.iter().zip(target_bytes.iter()) {
if hashed_byte > target_byte {
return false;
}
if hashed_byte < target_byte {
break;
}
}

true
}

0 comments on commit 0f567bc

Please sign in to comment.