openlark-auth 0.17.0

OpenLark 认证模块 - 提供令牌管理、缓存、验证和刷新功能
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
//! Authen相关数据模型
//!
//! 本模块包含用户认证相关的数据结构定义。

use chrono::{DateTime, Utc};
use openlark_core::api::responses::ApiResponseTrait;
use serde::{Deserialize, Serialize};

/// 用户信息响应
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct UserInfoResponse {
    /// 用户信息
    pub data: UserInfo,
}

/// 用户信息
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UserInfo {
    /// 用户Open ID
    pub open_id: String,
    /// 用户Union ID
    pub union_id: Option<String>,
    /// 用户ID
    pub user_id: Option<String>,
    /// 用户名
    pub name: Option<String>,
    /// 用户英文名/昵称
    pub en_name: Option<String>,
    /// 用户个人邮箱地址
    pub email: Option<String>,
    /// 用户企业邮箱地址
    pub enterprise_email: Option<String>,
    /// 用户手机号码
    pub mobile: Option<String>,
    /// 用户头像URL
    pub avatar_url: Option<String>,
    /// 用户头像
    pub avatar: Option<UserAvatar>,
    /// 用户状态
    pub status: Option<UserStatus>,
    /// 所属部门信息
    pub department_ids: Option<Vec<String>>,
    /// 群组信息
    pub group_ids: Option<Vec<String>>,
    /// 职位信息
    pub positions: Option<Vec<String>>,
    /// 工号
    pub employee_no: Option<String>,
    /// 钉钉UserId
    pub dingtalk_user_id: Option<String>,
    /// 企业扩展属性
    pub enterprise_extension: Option<UserEnterpriseExtension>,
    /// 自定义属性
    pub custom_attrs: Option<Vec<UserCustomAttr>>,
    /// 租户key
    pub tenant_key: Option<String>,
}

/// 用户头像
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UserAvatar {
    /// 头像72x72
    pub avatar_72: Option<String>,
    /// 头像240x240
    pub avatar_240: Option<String>,
    /// 头像640x640
    pub avatar_640: Option<String>,
    /// 头像原图
    pub avatar_origin: Option<String>,
}

/// 用户状态
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UserStatus {
    /// 是否激活
    pub is_activated: Option<bool>,
    /// 是否加入
    pub is_joined: Option<bool>,
    /// 是否预留
    pub is_reserved: Option<bool>,
    /// 是否离职
    pub is_exited: Option<bool>,
}

/// 企业扩展属性
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UserEnterpriseExtension {
    /// 入职时间
    pub hire_date: Option<DateTime<Utc>>,
    /// 所属国家
    pub location: Option<String>,
    /// 工作地点
    pub work_station: Option<String>,
    /// 工作地点ID
    pub work_station_id: Option<String>,
    /// 通讯地址
    pub address: Option<String>,
    /// 邮政编码
    pub postcode: Option<String>,
    /// 订购电话
    pub mobile_phone: Option<String>,
    /// 分机号
    pub extension_number: Option<String>,
    /// 联系电话
    pub contact_phone: Option<String>,
    /// 主要电话
    pub primary_phone: Option<String>,
    /// 紧急联系人
    pub emergency_contact: Option<String>,
    /// 紧急联系电话
    pub emergency_phone: Option<String>,
    /// 家庭电话
    pub home_phone: Option<String>,
}

/// 用户自定义属性
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UserCustomAttr {
    /// 属性Key
    pub key: Option<String>,
    /// 属性值
    pub value: Option<serde_json::Value>,
}

/// 用户访问令牌响应
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct UserAccessTokenResponse {
    /// 用户访问令牌
    pub user_access_token: String,
    /// 刷新令牌
    pub refresh_token: Option<String>,
    /// 令牌有效期(秒)
    pub expires_in: u64,
    /// 令牌类型
    pub token_type: Option<String>,
    /// 授权范围
    pub scope: Option<String>,
}

/// 用户访问令牌请求(v1版本)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UserAccessTokenV1Request {
    /// 授权码
    pub grant_code: String,
    /// 应用ID
    pub app_id: String,
    /// 应用密钥
    pub app_secret: String,
}

/// 用户访问令牌刷新请求(v1版本)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RefreshUserAccessTokenV1Request {
    /// 刷新令牌
    pub refresh_token: String,
    /// 应用ID
    pub app_id: String,
    /// 应用密钥
    pub app_secret: String,
}

/// OIDC用户访问令牌请求
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OidcUserAccessTokenRequest {
    /// 授权码
    pub code: String,
    /// 授权验证码
    pub code_verifier: Option<String>,
    /// 授权流程
    pub redirect_uri: Option<String>,
    /// 客户端ID
    pub client_id: Option<String>,
    /// 客户端密钥
    pub client_secret: Option<String>,
    /// 授权类型
    pub grant_type: Option<String>,
}

/// OIDC用户访问令牌刷新请求
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OidcRefreshUserAccessTokenRequest {
    /// 刷新令牌
    pub refresh_token: String,
    /// 客户端ID
    pub client_id: Option<String>,
    /// 客户端密钥
    pub client_secret: Option<String>,
    /// 授权类型
    pub grant_type: Option<String>,
}

/// 用户信息获取请求
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UserInfoRequest {
    /// 用户访问令牌
    pub user_access_token: String,
    /// 用户ID类型
    pub user_id_type: Option<String>,
}

impl PartialEq for UserInfo {
    fn eq(&self, other: &Self) -> bool {
        self.open_id == other.open_id
            && self.union_id == other.union_id
            && self.user_id == other.user_id
            && self.name == other.name
            && self.en_name == other.en_name
            && self.email == other.email
            && self.enterprise_email == other.enterprise_email
            && self.mobile == other.mobile
            && self.avatar_url == other.avatar_url
            && self.avatar == other.avatar
            && self.status == other.status
            && self.department_ids == other.department_ids
            && self.group_ids == other.group_ids
            && self.positions == other.positions
            && self.employee_no == other.employee_no
            && self.dingtalk_user_id == other.dingtalk_user_id
            && self.enterprise_extension == other.enterprise_extension
            && self.custom_attrs == other.custom_attrs
            && self.tenant_key == other.tenant_key
    }
}

impl PartialEq for UserAvatar {
    fn eq(&self, other: &Self) -> bool {
        self.avatar_72 == other.avatar_72
            && self.avatar_240 == other.avatar_240
            && self.avatar_640 == other.avatar_640
            && self.avatar_origin == other.avatar_origin
    }
}

impl PartialEq for UserStatus {
    fn eq(&self, other: &Self) -> bool {
        self.is_activated == other.is_activated
            && self.is_joined == other.is_joined
            && self.is_reserved == other.is_reserved
            && self.is_exited == other.is_exited
    }
}

impl PartialEq for UserEnterpriseExtension {
    fn eq(&self, other: &Self) -> bool {
        self.hire_date == other.hire_date
            && self.location == other.location
            && self.work_station == other.work_station
            && self.work_station_id == other.work_station_id
            && self.address == other.address
            && self.postcode == other.postcode
            && self.mobile_phone == other.mobile_phone
            && self.extension_number == other.extension_number
            && self.contact_phone == other.contact_phone
            && self.primary_phone == other.primary_phone
            && self.emergency_contact == other.emergency_contact
            && self.emergency_phone == other.emergency_phone
            && self.home_phone == other.home_phone
    }
}

impl PartialEq for UserCustomAttr {
    fn eq(&self, other: &Self) -> bool {
        self.key == other.key && self.value == other.value
    }
}

// 为所有响应类型实现ApiResponseTrait
impl ApiResponseTrait for UserInfoResponse {}
impl ApiResponseTrait for UserAccessTokenResponse {}

/// 用户令牌信息
#[derive(Debug, Clone)]
pub struct UserTokenInfo {
    /// 用户访问令牌
    pub user_access_token: String,
    /// 刷新令牌
    pub refresh_token: Option<String>,
    /// 过期时间
    pub expires_at: DateTime<Utc>,
    /// 令牌类型
    pub token_type: String,
    /// 授权范围
    pub scope: Option<String>,
    /// 获取时间
    pub created_at: DateTime<Utc>,
}

impl UserTokenInfo {
    /// 创建新的用户令牌信息
    pub fn new(
        user_access_token: String,
        expires_in: u64,
        token_type: String,
        refresh_token: Option<String>,
        scope: Option<String>,
    ) -> Self {
        let now = Utc::now();
        let expires_at = now + chrono::Duration::seconds(expires_in as i64);

        Self {
            user_access_token,
            refresh_token,
            expires_at,
            token_type,
            scope,
            created_at: now,
        }
    }

    /// 检查令牌是否已过期
    pub fn is_expired(&self) -> bool {
        Utc::now() >= self.expires_at
    }

    /// 检查令牌是否即将过期(提前5分钟)
    pub fn is_expiring_soon(&self) -> bool {
        let soon = Utc::now() + chrono::Duration::minutes(5);
        soon >= self.expires_at
    }

    /// 获取剩余有效时间(秒)
    pub fn remaining_seconds(&self) -> i64 {
        (self.expires_at - Utc::now()).num_seconds().max(0)
    }

    /// 检查是否有刷新令牌
    pub fn has_refresh_token(&self) -> bool {
        self.refresh_token.is_some()
    }
}

#[cfg(test)]
#[allow(unused_imports)]
mod tests {
    use super::*;

    #[test]
    fn test_user_info_serialization() {
        let user_info = UserInfo {
            open_id: "test_open_id".to_string(),
            union_id: Some("test_union_id".to_string()),
            user_id: Some("test_user_id".to_string()),
            name: Some("测试用户".to_string()),
            en_name: Some("Test User".to_string()),
            email: Some("test@example.com".to_string()),
            enterprise_email: Some("test@company.com".to_string()),
            mobile: Some("13800138000".to_string()),
            avatar_url: Some("https://example.com/avatar.jpg".to_string()),
            avatar: None,
            status: None,
            department_ids: None,
            group_ids: None,
            positions: None,
            employee_no: None,
            dingtalk_user_id: None,
            enterprise_extension: None,
            custom_attrs: None,
            tenant_key: None,
        };

        let json = serde_json::to_string(&user_info).unwrap();
        assert!(json.contains("test_open_id"));
        assert!(json.contains("测试用户"));
    }

    #[test]
    fn test_user_token_info() {
        let token = UserTokenInfo::new(
            "test_token".to_string(),
            3600,
            "Bearer".to_string(),
            Some("refresh_token".to_string()),
            Some("user_info".to_string()),
        );

        assert_eq!(token.user_access_token, "test_token");
        assert_eq!(token.token_type, "Bearer");
        assert!(token.has_refresh_token());
        assert!(!token.is_expired());
        assert!(token.remaining_seconds() > 0);
    }

    #[test]
    fn test_user_avatar() {
        let avatar = UserAvatar {
            avatar_72: Some("https://example.com/72.jpg".to_string()),
            avatar_240: Some("https://example.com/240.jpg".to_string()),
            avatar_640: Some("https://example.com/640.jpg".to_string()),
            avatar_origin: Some("https://example.com/original.jpg".to_string()),
        };

        let json = serde_json::to_string(&avatar).unwrap();
        assert!(json.contains("72.jpg"));
        assert!(json.contains("240.jpg"));
    }

    #[test]
    fn test_user_info_with_enterprise_email() {
        // 测试包含企业邮箱的用户信息
        let user_info = UserInfo {
            open_id: "test_open_id".to_string(),
            union_id: Some("test_union_id".to_string()),
            user_id: Some("test_user_id".to_string()),
            name: Some("测试用户".to_string()),
            en_name: Some("Test User".to_string()),
            email: Some("test@example.com".to_string()),
            enterprise_email: Some("test@company.com".to_string()),
            mobile: Some("13800138000".to_string()),
            avatar_url: Some("https://example.com/avatar.jpg".to_string()),
            avatar: None,
            status: None,
            department_ids: None,
            group_ids: None,
            positions: None,
            employee_no: None,
            dingtalk_user_id: None,
            enterprise_extension: None,
            custom_attrs: None,
            tenant_key: None,
        };

        // 序列化
        let json = serde_json::to_string(&user_info).unwrap();
        assert!(json.contains("enterprise_email"));
        assert!(json.contains("test@company.com"));

        // 反序列化
        let deserialized: UserInfo = serde_json::from_str(&json).expect("JSON 反序列化失败");
        assert_eq!(
            deserialized.enterprise_email,
            Some("test@company.com".to_string())
        );

        // 测试没有企业邮箱的情况
        let user_info_no_enterprise_email = UserInfo {
            enterprise_email: None,
            ..user_info
        };

        let json_no_enterprise = serde_json::to_string(&user_info_no_enterprise_email).unwrap();
        let deserialized_no_enterprise: UserInfo =
            serde_json::from_str(&json_no_enterprise).expect("JSON 反序列化失败");
        assert!(deserialized_no_enterprise.enterprise_email.is_none());
    }
}