diff --git a/Cargo.lock b/Cargo.lock index 8fe814f..360a254 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2233,6 +2233,7 @@ dependencies = [ "futures", "maud", "password-auth", + "rand 0.9.0", "rust-i18n", "serde", "sqlx", diff --git a/Cargo.toml b/Cargo.toml index 244cbdd..c226a0d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -21,6 +21,7 @@ password-auth = "1.0" tower-sessions-sqlx-store-chrono = { version = "0.14", features = ["sqlite"] } tracing-subscriber = "0.3" futures = "0.3" +rand = "0.9" [dev-dependencies] diff --git a/migration.sql b/migration.sql index 2cacfd6..f7a0cd4 100644 --- a/migration.sql +++ b/migration.sql @@ -5,7 +5,7 @@ CREATE TABLE IF NOT EXISTS station ( amount_people INTEGER, last_login DATETIME, ready BOOLEAN NOT NULL DEFAULT false, - pw TEXT NOT NULL DEFAULT (upper(hex(randomblob(4)))), + pw TEXT NOT NULL, lat REAL, lng REAL ); diff --git a/src/admin/station/mod.rs b/src/admin/station/mod.rs index 2ba2afc..e94597e 100644 --- a/src/admin/station/mod.rs +++ b/src/admin/station/mod.rs @@ -6,6 +6,11 @@ use crate::{ }; use axum::Router; use chrono::{DateTime, Local, NaiveDateTime, Utc}; +use rand::{ + distr::{Distribution, Uniform}, + rng, +}; + use serde::{Deserialize, Serialize}; use sqlx::{FromRow, SqlitePool}; @@ -78,8 +83,17 @@ impl Station { .unwrap(); } + fn generate_random_alphanumeric(length: usize) -> String { + let mut rng = rng(); + let chars: Vec = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ".chars().collect(); + let dist = Uniform::new(0, chars.len()).unwrap(); + + (0..length).map(|_| chars[dist.sample(&mut rng)]).collect() + } + pub(crate) async fn create(db: &SqlitePool, name: &str) -> Result<(), String> { - sqlx::query!("INSERT INTO station(name) VALUES (?)", name) + let code = Self::generate_random_alphanumeric(8); + sqlx::query!("INSERT INTO station(name, pw) VALUES (?, ?)", name, code) .execute(db) .await .map_err(|e| e.to_string())?;