feat: 增加令牌禁用、启用、续期功能并优化错误处理

- 增加禁用Token和更新Token有效期功能并优化返回类型
- 增加令牌禁用、启用和续期功能,并优化令牌信息查询的错误处理
This commit is contained in:
2025-08-19 15:08:07 +08:00
parent 3714ec6cd0
commit d0ccda69e2
2 changed files with 161 additions and 18 deletions

View File

@@ -1,4 +1,4 @@
use chrono::{Local, NaiveDateTime};
use chrono::{Duration, Local, NaiveDateTime};
use serde::Serialize;
use std::{fs, path::Path};
use welds::{connections::sqlite::SqliteClient, prelude::*};
@@ -118,12 +118,14 @@ impl Db {
pub async fn get_token_info(
&self,
token: &str,
) -> Result<Option<Authorize>, Box<dyn std::error::Error + Send + Sync>> {
) -> Result<
Option<DbState<Authorize>>,
Box<dyn std::error::Error + Send + Sync>,
> {
let row = Authorize::where_col(|p| p.token.equal(token))
.limit(1)
.run(&self.client)
.await?
.into_inners()
.into_iter()
.next();
@@ -146,4 +148,49 @@ impl Db {
let _created = auth.save(&self.client).await?;
Ok(auth.id)
}
/// 禁用 Token
pub async fn update_token_state(
&self,
token: &str,
state: i8,
) -> Result<bool, Box<dyn std::error::Error + Send + Sync>> {
let rows = Authorize::all()
.where_col(|a| a.token.equal(token))
.run(&self.client)
.await?;
if rows.is_empty() {
return Ok(false);
}
for mut row in rows {
row.disable = state;
row.save(&self.client).await?;
}
Ok(true)
}
/// 更新 Token 的有效期
pub async fn update_token_expiry(
&self,
token: &str,
days_to_add: i64,
) -> Result<
Option<DbState<Authorize>>,
Box<dyn std::error::Error + Send + Sync>,
> {
let auth_info = self.get_token_info(token).await?;
match auth_info {
Some(mut auth) => {
let current_expiry =
NaiveDateTime::parse_from_str(&auth.expire, "%Y-%m-%d %H:%M:%S")?;
let new_expiry = current_expiry + Duration::days(days_to_add);
auth.expire = new_expiry.format("%Y-%m-%d %H:%M:%S").to_string();
auth.save(&self.client).await?;
Ok(Some(auth))
}
None => Ok(None),
}
}
}