Skip to main content

sz_orm_auth/
lib.rs

1//! # SZ-ORM Auth — 认证授权
2//!
3//! 提供 JWT 令牌签发/校验与基于 RBAC 的权限控制(`Authorizer`/`RbacAuthorizer`),
4//! 涵盖用户、凭证与角色权限模型。
5//!
6//! ## 主要模块
7//!
8//! - [`auth`] — 用户、凭证等基础模型
9//! - [`jwt`] — JSON Web Token 签发与校验
10//! - [`authorizer`] — RBAC 授权器(含角色层级)
11//! - [`oauth2`] — OAuth2 授权码流程(RFC 6749)
12//! - [`mfa`] — 多因素认证(TOTP, RFC 6238)
13//! - [`token_store`] — 刷新令牌存储(轮换 + 撤销 + 重放检测)
14
15pub mod auth;
16pub mod authorizer;
17pub mod error;
18pub mod jwt;
19pub mod mfa;
20pub mod oauth2;
21pub mod token_store;
22
23pub use auth::*;
24pub use authorizer::{Authorizer, RbacAuthorizer};
25pub use error::AuthError;
26pub use mfa::{MfaManager, MfaSecret, TotpVerifier};
27pub use oauth2::{AuthorizationCode, AuthorizationRequest, OAuth2Server, TokenRequest};
28pub use token_store::{StoredToken, TokenFamilyError, TokenStore};
29
30#[cfg(test)]
31mod tests {
32    use super::*;
33
34    #[test]
35    fn test_module_exports() {
36        // Smoke test ensuring the public API compiles and is reachable.
37        let creds = Credentials::new("user", "pass");
38        assert_eq!(creds.username, "user");
39    }
40
41    #[test]
42    fn test_rbac_authorizer_via_lib_root() {
43        let authorizer = RbacAuthorizer::new();
44        let user = User::new(1, "user").with_permissions(vec!["read".to_string()]);
45
46        let can_read = authorizer.can(&user, "read", "resource");
47        let can_delete = authorizer.can(&user, "delete", "resource");
48
49        assert!(can_read.unwrap());
50        assert!(!can_delete.unwrap());
51    }
52
53    #[test]
54    fn test_rbac_authorizer_admin_via_lib_root() {
55        let authorizer = RbacAuthorizer::new();
56        let user = User::new(1, "admin").with_roles(vec!["admin".to_string()]);
57
58        let can_do_anything = authorizer.can(&user, "delete", "anything");
59
60        assert!(can_do_anything.unwrap());
61    }
62
63    #[test]
64    fn test_jwt_authenticator_via_lib_root() {
65        let auth = JwtAuthenticator::new("secret", "issuer", 3600);
66        let creds = Credentials::new("user", "pass");
67
68        let token = auth.authenticate(&creds).expect("authenticate");
69        assert!(!token.access_token.is_empty());
70
71        let user = auth.verify_token(&token.access_token).expect("verify");
72        assert_eq!(user.username, "user");
73    }
74
75    #[test]
76    fn test_jwt_encoder_via_lib_root() {
77        use jwt::{JwtClaims, JwtEncoder};
78        let encoder = JwtEncoder::new("lib-secret");
79        let claims = JwtClaims::new("lib-user", 9_999_999_999);
80        let token = encoder.encode(&claims).expect("encode");
81        let decoded = encoder.decode(&token).expect("decode");
82        assert_eq!(decoded.sub, "lib-user");
83    }
84}