refactor: 更新授权返回类型并增强令牌验证逻辑

- 将insert_authorize方法的返回值从i32改为Authorize类型。
- 为令牌创建逻辑添加过期检查和状态验证功能。
This commit is contained in:
2025-08-28 16:18:14 +08:00
parent 1d107a97ff
commit 6e8eb0aaaa
2 changed files with 41 additions and 30 deletions

View File

@@ -44,53 +44,63 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
Ok(())
}
fn check_datetime(t: &str) -> Result<bool, ParseError> {
let expire_time = NaiveDateTime::parse_from_str(&t, "%Y-%m-%d %H:%M:%S")?;
Ok(Local::now().naive_local() < expire_time)
}
fn is_valid(disable: i8, expire: &str) -> bool {
disable == 1 && check_datetime(expire).unwrap_or(false)
}
async fn create_token(
State(state): State<AppState>,
Query(args): Query<CreateToken>,
) -> (StatusCode, Json<CreateTokenInfo>) {
let exists = state
.db
.exists_project(&args.project, &args.device_id)
.await
.unwrap();
match exists {
Some(info) => {
return (
StatusCode::OK,
Json(CreateTokenInfo {
code: 200,
project: info.project,
device_id: info.device_id,
token: info.token,
msg: "token已存在请勿重复创建".to_owned(),
}),
)
}
None => (),
let CreateToken { project, device_id } = args;
if let Some(info) =
state.db.exists_project(&project, &device_id).await.unwrap()
{
let valid = is_valid(info.disable, &info.expire);
return (
StatusCode::OK,
Json(CreateTokenInfo {
code: 200,
project: info.project,
device_id: info.device_id,
token: info.token,
status: valid,
msg: "token已存在请勿重复创建".to_owned(),
}),
);
}
let str_time = get_current_datetime();
let exp_time = add_day(&str_time, 7).unwrap();
let token: String = state.generator.generate(16);
let _token_id = state
let create_auth = state
.db
.insert_authorize(InsertArgs {
project: args.project.clone(),
token: token.clone(),
device_id: args.device_id.clone(),
project,
token: token,
device_id,
disable: 1,
expire: exp_time,
insert_time: str_time,
})
.await;
.await
.unwrap();
let valid = is_valid(create_auth.disable, &create_auth.expire);
(
StatusCode::OK,
Json(CreateTokenInfo {
code: 200,
project: args.project,
device_id: args.device_id,
token,
project: create_auth.project,
device_id: create_auth.device_id,
token: create_auth.token,
status: valid,
msg: "token创建成功".to_owned(),
}),
)
@@ -341,6 +351,7 @@ struct CreateTokenInfo {
project: String,
device_id: String,
token: String,
status: bool,
msg: String,
}