From 2466d3db5dd2f301b61c9185e580ed23d0b3be3c Mon Sep 17 00:00:00 2001 From: matresnan <1358168412@qq.com> Date: Fri, 15 Aug 2025 18:49:04 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E6=B7=BB=E5=8A=A0=20axum=20=E6=A1=86?= =?UTF-8?q?=E6=9E=B6=E6=94=AF=E6=8C=81=E5=92=8C=20SQLite=20=E6=95=B0?= =?UTF-8?q?=E6=8D=AE=E5=BA=93=E5=8A=9F=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 添加 axum 框架支持并更新依赖版本 - 添加 axum、chrono、rand、serde 和 serde_json 依赖,更新 sqlx 和 tokio 配置,移除 warp 依赖。 - 添加授权数据数据库文件 - 添加数据库模块,实现 SQLite 连接、授权表创建及授权数据的增查功能。 - 添加随机Token生成器结构体及其实现,支持自定义字符集生成随机字符串。 - 重构项目以支持跨平台数据库路径配置并集成Token生成与验证功能 --- Cargo.lock | 311 ++++++++++++++++++--------------- Cargo.toml | 6 +- src/authorize_data/database.db | Bin 0 -> 20480 bytes src/db.rs | 111 ++++++++++++ src/generate.rs | 85 +++++++++ src/main.rs | 88 +++++----- 6 files changed, 419 insertions(+), 182 deletions(-) create mode 100644 src/authorize_data/database.db create mode 100644 src/db.rs create mode 100644 src/generate.rs diff --git a/Cargo.lock b/Cargo.lock index edc90c4..e98bb85 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -64,19 +64,17 @@ dependencies = [ "num-traits", ] -[[package]] -name = "atomic-waker" -version = "1.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" - [[package]] name = "authorize" version = "0.1.0" dependencies = [ + "axum", + "chrono", + "rand 0.9.2", + "serde", + "serde_json", "sqlx", "tokio", - "warp", "welds", ] @@ -86,6 +84,60 @@ version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8" +[[package]] +name = "axum" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "021e862c184ae977658b36c4500f7feac3221ca5da43e3f25bd04ab6c79a29b5" +dependencies = [ + "axum-core", + "bytes", + "form_urlencoded", + "futures-util", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-util", + "itoa", + "matchit", + "memchr", + "mime", + "percent-encoding", + "pin-project-lite", + "rustversion", + "serde", + "serde_json", + "serde_path_to_error", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tower", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "axum-core" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68464cd0412f486726fb3373129ef5d2993f90c34bc2bc1c1e9943b2f4fc7ca6" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "http-body-util", + "mime", + "pin-project-lite", + "rustversion", + "sync_wrapper", + "tower-layer", + "tower-service", + "tracing", +] + [[package]] name = "backtrace" version = "0.3.75" @@ -172,7 +224,9 @@ checksum = "c469d952047f47f91b68d1cba3f10d63c11d73e4636f24f08daf0278abf01c4d" dependencies = [ "android-tzdata", "iana-time-zone", + "js-sys", "num-traits", + "wasm-bindgen", "windows-link", ] @@ -445,7 +499,19 @@ checksum = "335ff9f135e4384c8150d6f27c6daed433577f86b4750418338c01a1a2528592" dependencies = [ "cfg-if", "libc", - "wasi", + "wasi 0.11.1+wasi-snapshot-preview1", +] + +[[package]] +name = "getrandom" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26145e563e54f2cadc477553f1ec5ee650b00862f0a58bcd12cbdc5f0ea2d2f4" +dependencies = [ + "cfg-if", + "libc", + "r-efi", + "wasi 0.14.2+wasi-0.2.4", ] [[package]] @@ -454,25 +520,6 @@ version = "0.31.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "07e28edb80900c19c28f1072f2e8aeca7fa06b23cd4169cefe1af5aa3260783f" -[[package]] -name = "h2" -version = "0.4.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f3c0b69cfcb4e1b9f1bf2f53f95f766e4661169728ec61cd3fe5a0166f2d1386" -dependencies = [ - "atomic-waker", - "bytes", - "fnv", - "futures-core", - "futures-sink", - "http", - "indexmap", - "slab", - "tokio", - "tokio-util", - "tracing", -] - [[package]] name = "hashbrown" version = "0.15.5" @@ -493,30 +540,6 @@ dependencies = [ "hashbrown", ] -[[package]] -name = "headers" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b3314d5adb5d94bcdf56771f2e50dbbc80bb4bdf88967526706205ac9eff24eb" -dependencies = [ - "base64", - "bytes", - "headers-core", - "http", - "httpdate", - "mime", - "sha1", -] - -[[package]] -name = "headers-core" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "54b4a22553d4242c49fddb9ba998a99962b5cc6f22cb5a3482bec22522403ce4" -dependencies = [ - "http", -] - [[package]] name = "heck" version = "0.5.0" @@ -611,7 +634,6 @@ dependencies = [ "bytes", "futures-channel", "futures-util", - "h2", "http", "http-body", "httparse", @@ -871,6 +893,12 @@ version = "0.4.27" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "13dc2df351e3202783a1fe0d44375f7295ffb4049267b0f3018346dc122a1d94" +[[package]] +name = "matchit" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3" + [[package]] name = "md-5" version = "0.10.6" @@ -893,16 +921,6 @@ version = "0.3.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" -[[package]] -name = "mime_guess" -version = "2.0.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f7c44f8e672c00fe5308fa235f821cb4198414e1c77935c1ab6948d3fd78550e" -dependencies = [ - "mime", - "unicase", -] - [[package]] name = "miniz_oxide" version = "0.8.9" @@ -919,7 +937,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "78bed444cc8a2160f01cbcf811ef18cac863ad68ae8ca62092e8db51d51c761c" dependencies = [ "libc", - "wasi", + "wasi 0.11.1+wasi-snapshot-preview1", "windows-sys 0.59.0", ] @@ -935,7 +953,7 @@ dependencies = [ "num-integer", "num-iter", "num-traits", - "rand", + "rand 0.8.5", "smallvec", "zeroize", ] @@ -1029,26 +1047,6 @@ version = "2.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e3148f5046208a5d56bcfc03053e3ca6334e51da8dfb19b6cdc8b306fae3283e" -[[package]] -name = "pin-project" -version = "1.1.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "677f1add503faace112b9f1373e43e9e054bfdd22ff1a63c1bc485eaec6a6a8a" -dependencies = [ - "pin-project-internal", -] - -[[package]] -name = "pin-project-internal" -version = "1.1.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6e918e4ff8c4549eb882f14b3a4bc8c8bc93de829416eacf579f1207a8fbf861" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.105", -] - [[package]] name = "pin-project-lite" version = "0.2.16" @@ -1124,6 +1122,12 @@ dependencies = [ "proc-macro2", ] +[[package]] +name = "r-efi" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" + [[package]] name = "rand" version = "0.8.5" @@ -1131,8 +1135,18 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404" dependencies = [ "libc", - "rand_chacha", - "rand_core", + "rand_chacha 0.3.1", + "rand_core 0.6.4", +] + +[[package]] +name = "rand" +version = "0.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6db2770f06117d490610c7488547d543617b21bfa07796d7a12f6f1bd53850d1" +dependencies = [ + "rand_chacha 0.9.0", + "rand_core 0.9.3", ] [[package]] @@ -1142,7 +1156,17 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" dependencies = [ "ppv-lite86", - "rand_core", + "rand_core 0.6.4", +] + +[[package]] +name = "rand_chacha" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" +dependencies = [ + "ppv-lite86", + "rand_core 0.9.3", ] [[package]] @@ -1151,7 +1175,16 @@ version = "0.6.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" dependencies = [ - "getrandom", + "getrandom 0.2.16", +] + +[[package]] +name = "rand_core" +version = "0.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "99d9a13982dcf210057a8a78572b2217b667c3beacbf3a0d8b454f6f82837d38" +dependencies = [ + "getrandom 0.3.3", ] [[package]] @@ -1176,7 +1209,7 @@ dependencies = [ "num-traits", "pkcs1", "pkcs8", - "rand_core", + "rand_core 0.6.4", "signature", "spki", "subtle", @@ -1201,12 +1234,6 @@ version = "1.0.20" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "28d3b2b1366ec20994f1fd18c3c594f05c5dd4bc44d8bb0c1c632c8d6829481f" -[[package]] -name = "scoped-tls" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e1cf6437eb19a8f4a6cc0f7dca544973b0b78843adbfeb3683d1a94a0024a294" - [[package]] name = "scopeguard" version = "1.2.0" @@ -1245,6 +1272,16 @@ dependencies = [ "serde", ] +[[package]] +name = "serde_path_to_error" +version = "0.1.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59fab13f937fa393d08645bf3a84bdfe86e296747b506ada67bb15f10f218b2a" +dependencies = [ + "itoa", + "serde", +] + [[package]] name = "serde_urlencoded" version = "0.7.1" @@ -1301,7 +1338,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de" dependencies = [ "digest", - "rand_core", + "rand_core 0.6.4", ] [[package]] @@ -1464,7 +1501,7 @@ dependencies = [ "memchr", "once_cell", "percent-encoding", - "rand", + "rand 0.8.5", "rsa", "serde", "sha1", @@ -1503,7 +1540,7 @@ dependencies = [ "md-5", "memchr", "once_cell", - "rand", + "rand 0.8.5", "serde", "serde_json", "sha2", @@ -1585,6 +1622,12 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "sync_wrapper" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" + [[package]] name = "synstructure" version = "0.13.2" @@ -1684,18 +1727,27 @@ dependencies = [ ] [[package]] -name = "tokio-util" -version = "0.7.16" +name = "tower" +version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "14307c986784f72ef81c89db7d9e28d6ac26d16213b109ea501696195e6e3ce5" +checksum = "d039ad9159c98b70ecfd540b2573b97f7f52c3e8d9f8ad57a24b916a536975f9" dependencies = [ - "bytes", "futures-core", - "futures-sink", + "futures-util", "pin-project-lite", + "sync_wrapper", "tokio", + "tower-layer", + "tower-service", + "tracing", ] +[[package]] +name = "tower-layer" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" + [[package]] name = "tower-service" version = "0.3.3" @@ -1740,12 +1792,6 @@ version = "1.18.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1dccffe3ce07af9386bfd29e80c0ab1a8205a2fc34e4bcd40364df902cfa8f3f" -[[package]] -name = "unicase" -version = "2.8.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "75b844d17643ee918803943289730bec8aac480150456169e647ed0b576ba539" - [[package]] name = "unicode-bidi" version = "0.3.18" @@ -1802,41 +1848,21 @@ version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" -[[package]] -name = "warp" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fbdb44bd9be779d5b40eb788578e318c40add8eaf639dfa3d443143f16e213af" -dependencies = [ - "bytes", - "futures-channel", - "futures-util", - "headers", - "http", - "http-body-util", - "hyper", - "hyper-util", - "log", - "mime", - "mime_guess", - "percent-encoding", - "pin-project", - "scoped-tls", - "serde", - "serde_json", - "serde_urlencoded", - "tokio", - "tokio-util", - "tower-service", - "tracing", -] - [[package]] name = "wasi" version = "0.11.1+wasi-snapshot-preview1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" +[[package]] +name = "wasi" +version = "0.14.2+wasi-0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9683f9a5a998d873c0d21fcbe3c083009670149a8fab228644b8bd36b2c48cb3" +dependencies = [ + "wit-bindgen-rt", +] + [[package]] name = "wasite" version = "0.1.0" @@ -2144,6 +2170,15 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" +[[package]] +name = "wit-bindgen-rt" +version = "0.39.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f42320e61fe2cfd34354ecb597f86f413484a798ba44a8ca1165c58d42da6c1" +dependencies = [ + "bitflags", +] + [[package]] name = "writeable" version = "0.6.1" diff --git a/Cargo.toml b/Cargo.toml index 173fdf9..31bfe61 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,7 +4,11 @@ version = "0.1.0" edition = "2024" [dependencies] +axum = "0.8.4" +chrono = "0.4.41" +rand = "0.9.2" +serde = { version = "1.0.219", features = ["derive"] } +serde_json = "1.0.142" sqlx = { version = "0.8.6", features = ["runtime-tokio", "chrono", "sqlite"] } tokio = { version = "1.47.1", features = ["full"] } -warp = { version = "0.4.1", features = ["server"] } welds = { version = "0.4.17", features = ["sqlite"] } diff --git a/src/authorize_data/database.db b/src/authorize_data/database.db new file mode 100644 index 0000000000000000000000000000000000000000..a288a2de313464f7ade5845f95dfd4083bc03762 GIT binary patch literal 20480 zcmeI&O^?z*7zgkfs9-h$ym2ra#)DyT!L;B;@nEdl7{bdUb`v=@T{;^_m(ne>hH}&R zsWvfwCKEq^Q#KH~>xKh2@}G3VGsE=B%x_Ll(vKfHLUMLC3CFHv4f23cN?tQY2+62^ zPxWO>sX$u})Gu9&?+P>I={(5gIni=gB>y`<&Ryl7+_f0<5P$##AOHafKmY;|fB*y_ z@IL`Roh_Ej^!r2Uo}TmR#W{C<$Kz+hPY$%V1Ix56W}9z17E7!<@ZB+IlFuXyLNRv3 zh<)WzmB}c$p02Xfi5D$aRGM0**ez2ce2>pm8dWwr?xmb8#!e!yVsFsDZjYn{wUt_`Y?TS*Xw^S_FYwPR(`yq*_!tFYxQjFy)|I{L91&HhOBK3nR#L#w|Xi|*Xr5TTW>*OtEfS;_+`{#2vMb4Y~L%5Fy{RO88SAN=FKH!-<56BUEzgTD1IMQutMv7oMvC z4FV8=00bZa0SG_<0uX=z1R$^@0;ZNFkM~QD8aAKG{&fLw#BrNP#=AusuIol!Z#HX2 zz1C1s{ivqDs2R_gQGcoH>M_&Xr$}v|f^MB6uK#J_4^a;q1Rwwb2tWV=5P$##AOHaf zKmY=}B9No$5?y@ 建文件 -> 建表 -> 返回 Self + pub async fn new( + db_path: impl AsRef, + ) -> Result> { + let db_path = db_path.as_ref(); + + let parent = Path::new(db_path).parent().unwrap(); + if !parent.exists() { + fs::create_dir_all(parent)?; + } + if !Path::new(db_path).exists() { + fs::File::create(db_path)?; + } + + let conn_str = format!("sqlite://{db_path}"); + let client = welds::connections::sqlite::connect(&conn_str).await?; + + client + .execute( + r#" + CREATE TABLE IF NOT EXISTS authorize ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + project TEXT NOT NULL, + key TEXT NOT NULL, + device_id TEXT NOT NULL, + expire TEXT NOT NULL, + insert_time TEXT NOT NULL + ) + "#, + &[], + ) + .await?; + + Ok(Db { client }) + } + + /// 判断 token 是否存在 + pub async fn verify_token( + &self, + token: &str, + ) -> Result> { + let rows = Authorize::where_col(|p| p.key.equal(token)) + .limit(1) + .run(&self.client) + .await?; + Ok(!rows.is_empty()) + } + + /// 查询 token 的详细信息,返回 Option 如果存在 + pub async fn get_token_info( + &self, + token: &str, + ) -> Result, Box> { + let rows: Vec> = + Authorize::where_col(|p| p.key.equal(token)) + .limit(1) + .run(&self.client) + .await?; + + if let Some(auth) = rows.into_inners().into_iter().next() { + // 转 JSON + let json_str = serde_json::to_string(&auth)?; + Ok(Some(json_str)) + } else { + Ok(None) + } + } + + /// 插入新的授权数据 + pub async fn insert_authorize( + &self, + project: &str, + key: &str, + device_id: &str, + expire: &str, + insert_time: &str, + ) -> Result> { + let mut auth = Authorize::new(); + auth.project = project.to_string(); + auth.key = key.to_string(); + auth.device_id = device_id.to_string(); + auth.expire = expire.to_string(); + auth.insert_time = insert_time.to_string(); + + let _created = auth.save(&self.client).await?; + Ok(auth.id) + } +} diff --git a/src/generate.rs b/src/generate.rs new file mode 100644 index 0000000..329ba23 --- /dev/null +++ b/src/generate.rs @@ -0,0 +1,85 @@ +use rand::Rng; + +/// 随机Token生成器结构体 +pub struct TokenGenerator { + uppercase: bool, + lowercase: bool, + numbers: bool, +} + +impl TokenGenerator { + /// 创建新的TokenGenerator实例 + pub fn new() -> Self { + Self { + uppercase: true, + lowercase: true, + numbers: true, + } + } + + /// 设置是否包含大写字母 + pub fn with_uppercase(mut self, include: bool) -> Self { + self.uppercase = include; + self + } + + /// 设置是否包含小写字母 + pub fn with_lowercase(mut self, include: bool) -> Self { + self.lowercase = include; + self + } + + /// 设置是否包含数字 + pub fn with_numbers(mut self, include: bool) -> Self { + self.numbers = include; + self + } + + /// 生成随机token + pub fn generate(&self, length: usize) -> String { + let charset = self.build_charset(); + if charset.is_empty() { + // 如果没有选择任何字符类型,使用默认字符集 + return self.generate_with_default_charset(length); + } + + let mut rng = rand::rng(); + (0..length) + .map(|_| { + let idx = rng.random_range(0..charset.len()); + charset[idx] as char + }) + .collect() + } + + /// 构建字符集 + fn build_charset(&self) -> Vec { + let mut charset = Vec::new(); + + if self.uppercase { + charset.extend_from_slice(b"ABCDEFGHIJKLMNOPQRSTUVWXYZ"); + } + if self.lowercase { + charset.extend_from_slice(b"abcdefghijklmnopqrstuvwxyz"); + } + if self.numbers { + charset.extend_from_slice(b"0123456789"); + } + + charset + } + + /// 使用默认字符集生成token + fn generate_with_default_charset(&self, length: usize) -> String { + let charset = + b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; + let mut rng = rand::rng(); + + (0..length) + .map(|_| { + let idx = rng.random_range(0..charset.len()); + charset[idx] as char + }) + .collect() + } +} diff --git a/src/main.rs b/src/main.rs index cab40fe..b7e41e4 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,8 +1,13 @@ -use std::{fs, path::Path}; +use chrono::{prelude::*, Duration, ParseError}; +use std::env; +use token_generator::TokenGenerator; -use warp::Filter; +use axum::{routing::get, Router}; use welds::prelude::*; +mod db; +mod generate; + #[derive(WeldsModel)] #[welds(table = "authorize")] pub struct Authorize { @@ -17,53 +22,50 @@ pub struct Authorize { #[tokio::main] async fn main() -> Result<(), Box> { - let db_path = "C:/Users/admin/Desktop/database.db"; + // 根据操作系统选择数据库路径 + let windows_path: String = env::current_dir() + .expect("无法获取当前目录") + .join("authorize_data/database.db") + .to_string_lossy() + .into_owned(); - if let Some(parent_dir) = Path::new(db_path).parent() { - if !parent_dir.exists() { - fs::create_dir_all(parent_dir)?; - println!("已创建目录: {:?}", parent_dir); - } - } + // 现在可以取切片 + let db_path: &str = if cfg!(target_os = "windows") { + &windows_path + } else if cfg!(target_os = "linux") { + "/usr/local/etc/authorize_data/database.db" + } else { + panic!("不支持的操作系统"); + }; - if !Path::new(db_path).exists() { - fs::File::create(db_path)?; - println!("已创建空数据库文件: {}", db_path); - } + let db = db::Db::new(db_path).await?; - let connection_string = format!("sqlite://{db_path}"); - let client = welds::connections::connect(connection_string).await?; + // // build our application with a single route + // let app = Router::new().route("/", get(|| async { "Hello, World!" })); - // 先执行建表 SQL(如果表不存在) - client - .execute( - r#" - CREATE TABLE IF NOT EXISTS authorize ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - project TEXT NOT NULL, - key TEXT NOT NULL, - device_id TEXT NOT NULL, - expire TEXT NOT NULL, - insert_time TEXT NOT NULL - ) - "#, - &[], - ) - .await?; + // // run our app with hyper, listening globally on port 3000 + // let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap(); + // axum::serve(listener, app).await.unwrap(); - let mut authorize = Authorize::new(); - authorize.id = 0; - authorize.project = "TestProject1".to_string(); - authorize.key = "TestKey1".to_string(); - authorize.device_id = "Device001".to_string(); - authorize.expire = "2099-12-31".to_string(); - authorize.insert_time = "2025-08-14 12:00:00".to_string(); - authorize.save(client.as_ref()).await?; + let generator = TokenGenerator::new() + .with_uppercase(true) + .with_lowercase(true) + .with_numbers(true); - // GET /hello/warp => 200 OK with body "Hello, warp!" - let hello = - warp::path!("hello" / String).map(|name| format!("Hello, {}!", name)); + let token = generator.generate(16); + println!("token: {}", token); - warp::serve(hello).run(([127, 0, 0, 1], 3030)).await; + let result = db.get_token_info("TestKey1").await.unwrap(); + println!("{:?}", result); Ok(()) } + +fn get_current_datetime() -> String { + Local::now().format("%Y-%m-%d %H:%M:%S").to_string() +} + +fn add_day(t: &String, days: i64) -> Result { + let date_time = DateTime::parse_from_str(t, "%Y-%m-%d %H:%M:%S")?; + let new_time = date_time + Duration::days(days); + Ok(new_time.to_string()) +}