pub trait Guard: Send + Sync {
// Required method
fn check(&self, req: &Request<Body>) -> Result<(), GuardError>;
}Expand description
Guard trait — NestJS 风格的守卫接口
守卫在 Auth 中间件之后执行,用于鉴权决策(allow/deny)。
§同步 trait 设计
check 为同步方法,因为:
- 决策基于 request extensions(已在 Auth 中间件中预加载)
- 不需要 I/O(DB 查询由业务层中间件完成,结果存入
UserContext) - 对齐
sz-orm-auth的Authorizertrait 设计
如需异步 DB 查询,应在 Guard 之前的中间件中预加载权限信息到 UserContext。
§PHP 对齐
PHP 端无直接对应物。PHP 鉴权分散在各应用的 Controller 基类:
addons\BaseController::checkLogin:登录校验(对齐AuthGuard)app\szoa\controller\Base::checkAuth:权限校验(对齐PermissionGuard)
sz-rust 将鉴权抽象为独立 Guard 层,便于复用和组合。
Required Methods§
Sourcefn check(&self, req: &Request<Body>) -> Result<(), GuardError>
fn check(&self, req: &Request<Body>) -> Result<(), GuardError>
检查请求是否通过守卫
返回 Ok(()) 表示通过,Err(GuardError) 表示拒绝。
§实现约定
- 应先检查
AuthenticatedUser是否存在(登录校验) - 再检查
UserContext中的权限信息 is_super=true应绕过所有权限检查(对齐 PHPis_super=1)
Dyn Compatibility§
This trait is dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety".