feat: 引入 InsertArgs 聚合授权数据并开放 /create API

- 引入 InsertArgs 结构体并替换 insert_authorize 的多参数列表,改用入参聚合方式传递授权数据。
- 启动提供 /create 接口的 API 服务并用数据库保存生成的令牌
This commit is contained in:
2025-08-16 12:01:04 +08:00
parent 2466d3db5d
commit 25ca58760b
2 changed files with 93 additions and 31 deletions

View File

@@ -15,6 +15,14 @@ pub struct Authorize {
pub insert_time: String, pub insert_time: String,
} }
pub(crate) struct InsertArgs {
pub project: String,
pub key: String,
pub device_id: String,
pub expire: String,
pub insert_time: String,
}
/// 包装类,内部持有 SQLite 连接 /// 包装类,内部持有 SQLite 连接
pub struct Db { pub struct Db {
client: SqliteClient, client: SqliteClient,
@@ -92,18 +100,14 @@ impl Db {
/// 插入新的授权数据 /// 插入新的授权数据
pub async fn insert_authorize( pub async fn insert_authorize(
&self, &self,
project: &str, args: InsertArgs,
key: &str,
device_id: &str,
expire: &str,
insert_time: &str,
) -> Result<i32, Box<dyn std::error::Error>> { ) -> Result<i32, Box<dyn std::error::Error>> {
let mut auth = Authorize::new(); let mut auth = Authorize::new();
auth.project = project.to_string(); auth.project = args.project.to_string();
auth.key = key.to_string(); auth.key = args.key.to_string();
auth.device_id = device_id.to_string(); auth.device_id = args.device_id.to_string();
auth.expire = expire.to_string(); auth.expire = args.expire.to_string();
auth.insert_time = insert_time.to_string(); auth.insert_time = args.insert_time.to_string();
let _created = auth.save(&self.client).await?; let _created = auth.save(&self.client).await?;
Ok(auth.id) Ok(auth.id)

View File

@@ -1,8 +1,12 @@
use axum::{
extract::{Query, State},
http::StatusCode,
routing::get,
Json, Router,
};
use chrono::{prelude::*, Duration, ParseError}; use chrono::{prelude::*, Duration, ParseError};
use std::env; use serde::{Deserialize, Serialize};
use token_generator::TokenGenerator; use std::{env, sync::Arc};
use axum::{routing::get, Router};
use welds::prelude::*; use welds::prelude::*;
mod db; mod db;
@@ -38,34 +42,88 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
panic!("不支持的操作系统"); panic!("不支持的操作系统");
}; };
let db = db::Db::new(db_path).await?; let db = Arc::new(db::Db::new(db_path).await?);
// // build our application with a single route let generator = Arc::new(
// let app = Router::new().route("/", get(|| async { "Hello, World!" })); generate::TokenGenerator::new()
.with_uppercase(true)
.with_lowercase(true)
.with_numbers(true),
);
// // run our app with hyper, listening globally on port 3000 let state = AppState { db, generator };
// let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
// axum::serve(listener, app).await.unwrap();
let generator = TokenGenerator::new() // build our application with a single route
.with_uppercase(true) let app = Router::new()
.with_lowercase(true) .route("/create", get(create_token))
.with_numbers(true); .with_state(state);
let token = generator.generate(16); // run our app with hyper, listening globally on port 3009
println!("token: {}", token); let listener = tokio::net::TcpListener::bind("127.0.0.1:3009")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
let result = db.get_token_info("TestKey1").await.unwrap(); // let token = generator.generate(16);
println!("{:?}", result); // println!("token: {}", token);
// let result = db.get_token_info("TestKey1").await.unwrap();
// println!("{:?}", result);
Ok(()) Ok(())
} }
async fn create_token(
State(state): State<AppState>,
Query(args): Query<CreateToken>,
) -> (StatusCode, Json<CreateResult>) {
let current = get_current_datetime();
let exp_time = add_day(&current, 7).unwrap();
let token: String = state.generator.generate(16);
let _ = state
.db
.insert_authorize(db::InsertArgs {
project: args.project,
key: token,
device_id: args.device_id,
expire: current,
insert_time: exp_time,
})
.await;
(
StatusCode::OK,
Json(CreateResult {
code: 200,
msg: "创建成功".to_owned(),
}),
)
}
fn get_current_datetime() -> String { fn get_current_datetime() -> String {
Local::now().format("%Y-%m-%d %H:%M:%S").to_string() Local::now().format("%Y-%m-%d %H:%M:%S").to_string()
} }
fn add_day(t: &String, days: i64) -> Result<String, ParseError> { fn add_day(t: &str, days: i64) -> Result<String, ParseError> {
let date_time = DateTime::parse_from_str(t, "%Y-%m-%d %H:%M:%S")?; let date_time = NaiveDateTime::parse_from_str(t, "%Y-%m-%d %H:%M:%S")?;
let new_time = date_time + Duration::days(days); let new_time = date_time + Duration::days(days);
Ok(new_time.to_string()) Ok(new_time.format("%Y-%m-%d %H:%M:%S").to_string())
}
#[derive(Deserialize)]
struct CreateToken {
project: String,
device_id: String,
}
#[derive(Serialize)]
struct CreateResult {
code: i16,
msg: String,
}
#[derive(Clone)]
struct AppState {
db: Arc<db::Db>,
generator: Arc<generate::TokenGenerator>,
} }