| 1 | //! 个人访问令牌的发放与撤销(0014)。 |
| 2 | //! |
| 3 | //! **走的是账户级路由,不是知识库级**——令牌属于人,而人可以进好几个库。 |
| 4 | //! 哪几个库归令牌自己的 `kb_ids` 管,那是收窄,不是授权。 |
| 5 | |
| 6 | use axum::extract::{Path, State}; |
| 7 | use axum::Json; |
| 8 | use serde::Deserialize; |
| 9 | use serde_json::json; |
| 10 | use uuid::Uuid; |
| 11 | |
| 12 | use crate::auth::AuthUser; |
| 13 | use crate::error::ApiResult; |
| 14 | use crate::state::AppState; |
| 15 | |
| 16 | #[derive(Deserialize)] |
| 17 | pub struct IssueReq { |
| 18 | pub name: String, |
| 19 | /// read | write。缺省只读——要让 agent 写进账本,得显式勾 |
| 20 | #[serde(default = "default_scope")] |
| 21 | pub scope: String, |
| 22 | /// 缺省 = 这个人能进的全部库 |
| 23 | #[serde(default)] |
| 24 | pub kb_ids: Option<Vec<Uuid>>, |
| 25 | /// 多少天后过期。缺省 90 天;显式给 0 表示不过期 |
| 26 | #[serde(default = "default_days")] |
| 27 | pub expires_in_days: i64, |
| 28 | } |
| 29 | fn default_scope() -> String { |
| 30 | "read".into() |
| 31 | } |
| 32 | /// 90 天。**不过期是能选的,但不是缺省**——一枚配在别人笔记本上的钥匙, |
| 33 | /// 忘了它存在是常态 |
| 34 | fn default_days() -> i64 { |
| 35 | 90 |
| 36 | } |
| 37 | |
| 38 | /// 发一枚。**明文只在这一次的响应里出现**,之后库里只有哈希。 |
| 39 | pub async fn issue( |
| 40 | State(state): State<AppState>, |
| 41 | AuthUser(user): AuthUser, |
| 42 | Json(req): Json<IssueReq>, |
| 43 | ) -> ApiResult<Json<serde_json::Value>> { |
| 44 | let expires_at = (req.expires_in_days > 0) |
| 45 | .then(|| chrono::Utc::now() + chrono::Duration::days(req.expires_in_days)); |
| 46 | let (view, plain) = utopia_store::tokens::issue( |
| 47 | &state.pool, |
| 48 | user.id, |
| 49 | &req.name, |
| 50 | &req.scope, |
| 51 | req.kb_ids.as_deref(), |
| 52 | expires_at, |
| 53 | ) |
| 54 | .await?; |
| 55 | let _ = utopia_store::audit::record( |
| 56 | &state.pool, |
| 57 | None, |
| 58 | user.id, |
| 59 | "token.issued", |
| 60 | "personal_token", |
| 61 | Some(view.id), |
| 62 | json!({ "name": view.name, "scope": view.scope }), |
| 63 | ) |
| 64 | .await; |
| 65 | // `token` 这个字段只在这里出现一次。列表接口永远给不出它 |
| 66 | Ok(Json(json!({ "token": plain, "info": view }))) |
| 67 | } |
| 68 | |
| 69 | pub async fn list( |
| 70 | State(state): State<AppState>, |
| 71 | AuthUser(user): AuthUser, |
| 72 | ) -> ApiResult<Json<serde_json::Value>> { |
| 73 | let tokens = utopia_store::tokens::list(&state.pool, user.id).await?; |
| 74 | Ok(Json(json!({ "tokens": tokens }))) |
| 75 | } |
| 76 | |
| 77 | pub async fn revoke( |
| 78 | State(state): State<AppState>, |
| 79 | AuthUser(user): AuthUser, |
| 80 | Path(token_id): Path<Uuid>, |
| 81 | ) -> ApiResult<Json<serde_json::Value>> { |
| 82 | utopia_store::tokens::revoke(&state.pool, user.id, token_id).await?; |
| 83 | let _ = utopia_store::audit::record( |
| 84 | &state.pool, |
| 85 | None, |
| 86 | user.id, |
| 87 | "token.revoked", |
| 88 | "personal_token", |
| 89 | Some(token_id), |
| 90 | json!({}), |
| 91 | ) |
| 92 | .await; |
| 93 | Ok(Json(json!({ "ok": true }))) |
| 94 | } |