Skip to content

Commit

Permalink
use random string for code
Browse files Browse the repository at this point in the history
  • Loading branch information
pabueco committed Jan 31, 2024
1 parent 8ee14d0 commit df94ee7
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 22 deletions.
20 changes: 1 addition & 19 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,9 @@ indoc = "2.0.4"
http = "1.0.0"
serde_json = "1.0.111"
base64 = "0.21.7"
svix-ksuid = "0.8.0"
time = { version = "0.3", features = ["wasm-bindgen"] }
serde_repr = "0.1.18"
rand = "0.8.5"

[features]
default = ["console_error_panic_hook"]
Expand Down
28 changes: 26 additions & 2 deletions src/routes/create.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ use base64::engine::general_purpose::URL_SAFE;
use base64::Engine as _;
use http::StatusCode;
use serde::{Deserialize, Serialize};
use svix_ksuid::{KsuidLike, KsuidMs};
use worker::*;
use rand::distributions::{Alphanumeric, DistString};

use crate::error::create_error_json;
use crate::model::{create_database, ShortlinkMode};
Expand All @@ -16,6 +16,12 @@ enum CreateShortcodeJsonBody {
Repl(ReplState),
}

fn generate_code() -> String {
let string = Alphanumeric.sample_string(&mut rand::thread_rng(), 13);

string
}

pub async fn create_shortcode(mut req: Request, ctx: RouteContext<()>) -> worker::Result<Response> {
let Ok(body) = req.json::<CreateShortcodeJsonBody>().await else {
return create_error_json(
Expand All @@ -29,12 +35,30 @@ pub async fn create_shortcode(mut req: Request, ctx: RouteContext<()>) -> worker
CreateShortcodeJsonBody::Repl(_) => ShortlinkMode::Repl,
};

let code = KsuidMs::new(None, None).to_string();
let s = serde_json::to_vec(&body)?;
let data = URL_SAFE.encode(&s);

let db = create_database(&ctx.env).await?;

// Generate a unique shortcode.
let mut attempts = 0;
let max_attempts = 10;
let mut code = generate_code();

while let Ok(Some(_)) = db
.query_opt("select code from shortcode where code = $1", &[&code])
.await
{
code = generate_code();
attempts += 1;
if attempts >= max_attempts {
return create_error_json(
StatusCode::INTERNAL_SERVER_ERROR,
"Failed to generate unique shortcode",
);
}
}

if let Err(err) = db
.execute(
"insert into shortcode(code, mode, data) values ($1, $2, $3);",
Expand Down

0 comments on commit df94ee7

Please sign in to comment.