Files
core/test/rust/performance/auth/reference.rs
T
2026-11-03 03:32:07 +00:00

115 lines
3.6 KiB
Rust

// 手写 Rust 重做 Provider 的查询、完整行解码和身份判断;不调用生成函数。
use dever_runtime::{
api::Failure as ApiFailure,
auth::{self, Claims, Identity},
};
struct RustAccount {
id: dever_runtime::database::Id<AUTH_USER_MODEL>,
_created_at: dever_runtime::time::calendar::DateTime,
subject: String,
_session: String,
_active: bool,
}
async fn rust_verify(
context: &mut auth::Context<'_>,
claims: Claims,
scope: &Scope<'_>,
registry: &Arc<Registry>,
) -> Result<(), ApiFailure> {
if context.verifier() != Some("bench.account.verify") {
return Err(ApiFailure(500));
}
let mut database = DbContext::new(registry.clone());
let executor = database
.on(ACCOUNT_BINDING, scope)
.await
.map_err(|_| ApiFailure(500))?;
let mut rows = executor.query(scope,
"SELECT \"id\",\"created_at\",\"subject\",\"session\",\"active\" FROM \"bench_account_model\" WHERE (((\"subject\" IS ?1) AND (\"session\" IS ?2)) AND (\"active\" IS ?3)) ORDER BY \"id\" DESC LIMIT 1",
vec![Parameter::Text(claims.subject), Parameter::Text(claims.session), Parameter::Integer(1)], 1,
|row| Ok(RustAccount {
id: dever_runtime::database::Id(row.get::<_, i64>(0)?),
_created_at: dever_runtime::time::calendar::DateTime::from_millis(row.get::<_, i64>(1)?).map_err(|_| dever_runtime::database::Error::new(dever_runtime::database::Kind::InvalidData, "invalid stored DateTime"))?,
subject: row.get(2)?, _session: row.get(3)?, _active: row.get(4)?,
})
).await.map_err(|_| ApiFailure(500))?;
let row = rows.pop().ok_or(ApiFailure(401))?;
context
.establish(Identity {
id: row.subject,
user_id: Some(row.id.0),
tenant_id: None,
})
.map_err(|error| ApiFailure(error.status()))
}
// 输出所有字段,防止只读长度让优化器删掉 Dever 或 Rust 的记录转换。
type PermissionView = [String; 7];
async fn rust_permissions(
context: &mut auth::Context<'_>,
scope: &Scope<'_>,
database: &mut DbContext,
) -> Vec<PermissionView> {
dever_runtime::authorization::permissions(database, AUTH_BINDING, scope, context, true)
.await
.unwrap()
.into_iter()
.map(|value| {
[
value.key,
value.component,
value.domain,
value.site,
value.action,
value.method,
value.kind,
]
})
.collect()
}
async fn permissions(
generated: bool,
context: &mut auth::Context<'_>,
scope: &Scope<'_>,
database: &mut DbContext,
) -> Vec<PermissionView> {
if generated {
GENERATED_PERMISSIONS(scope, database, context)
.await
.unwrap()
.into_iter()
.map(|value| {
[
value.field0,
value.field1,
value.field2,
value.field3,
value.field4,
value.field5,
value.field6,
]
})
.collect()
} else {
rust_permissions(context, scope, database).await
}
}
async fn verify(
generated: bool,
context: &mut auth::Context<'_>,
claims: Claims,
scope: &Scope<'_>,
registry: &Arc<Registry>,
) -> Result<(), ApiFailure> {
if generated {
api_verify(context, claims, scope, registry).await
} else {
rust_verify(context, claims, scope, registry).await
}
}