Skip to main content

flare_core/server/auth/
authenticator.rs

1//! 认证器 Trait
2//!
3//! 定义认证接口,允许用户实现自定义的 token 验证逻辑
4
5use crate::common::device::DeviceInfo;
6use crate::common::error::Result;
7use async_trait::async_trait;
8
9/// 认证结果
10#[derive(Debug, Clone)]
11pub struct AuthResult {
12    /// 是否验证通过
13    pub authenticated: bool,
14    /// 用户 ID(如果验证通过)
15    pub user_id: Option<String>,
16    /// 错误消息(如果验证失败)
17    pub error_message: Option<String>,
18    /// 用户元数据(可选,用于存储额外的用户信息)
19    pub user_metadata: Option<std::collections::HashMap<String, String>>,
20}
21
22impl AuthResult {
23    /// 创建成功的认证结果
24    pub fn success(user_id: Option<String>) -> Self {
25        Self {
26            authenticated: true,
27            user_id,
28            error_message: None,
29            user_metadata: None,
30        }
31    }
32
33    /// 创建成功的认证结果(带元数据)
34    pub fn success_with_metadata(
35        user_id: Option<String>,
36        metadata: std::collections::HashMap<String, String>,
37    ) -> Self {
38        Self {
39            authenticated: true,
40            user_id,
41            error_message: None,
42            user_metadata: Some(metadata),
43        }
44    }
45
46    /// 创建失败的认证结果
47    pub fn failure(error_message: String) -> Self {
48        Self {
49            authenticated: false,
50            user_id: None,
51            error_message: Some(error_message),
52            user_metadata: None,
53        }
54    }
55}
56
57/// 认证器 Trait
58///
59/// 实现此 trait 以提供自定义的 token 验证逻辑
60/// 例如:JWT 验证、数据库查询、Redis 验证等
61#[async_trait]
62pub trait Authenticator: Send + Sync {
63    /// 验证 token
64    ///
65    /// # 参数
66    /// - `token`: 客户端提供的 token(从 CONNECT 消息的 metadata 中提取)
67    /// - `connection_id`: 连接 ID
68    /// - `device_info`: 设备信息(可选,客户端可能提供)
69    /// - `metadata`: CONNECT 消息的其他元数据(可选)
70    ///
71    /// # 返回
72    /// - `Ok(AuthResult)`: 认证结果
73    /// - `Err`: 认证过程出错(非验证失败,而是系统错误)
74    async fn authenticate(
75        &self,
76        token: &str,
77        connection_id: &str,
78        device_info: Option<&DeviceInfo>,
79        metadata: Option<&std::collections::HashMap<String, Vec<u8>>>,
80    ) -> Result<AuthResult>;
81
82    /// 检查连接是否已验证(可选,用于验证状态管理)
83    ///
84    /// 默认实现返回 true(假设验证通过后连接状态由 ConnectionManager 管理)
85    /// 如果需要自定义验证状态管理(如 Redis、数据库),可以覆盖此方法
86    async fn is_authenticated(&self, connection_id: &str) -> Result<bool> {
87        let _ = connection_id;
88        Ok(true)
89    }
90
91    /// 使连接失效(可选,用于主动撤销认证)
92    ///
93    /// 默认实现不做任何操作
94    /// 如果需要支持主动撤销认证(如用户登出、token 撤销),可以覆盖此方法
95    async fn revoke_authentication(&self, connection_id: &str) -> Result<()> {
96        let _ = connection_id;
97        Ok(())
98    }
99}