openlark-security 0.17.0

飞书开放平台安全认证服务模块 - 身份认证、权限管理、安全审计 (44 APIs)
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
//! 门禁用户管理 API
//!
//! 提供用户信息的增删改查功能。

use openlark_core::error::api_error;
use std::sync::Arc;

/// 用户管理服务
#[derive(Debug)]
pub struct UsersService {
    config: Arc<crate::models::SecurityConfig>,
}

impl UsersService {
    /// 创建新的用户管理服务实例
    pub fn new(config: Arc<crate::models::SecurityConfig>) -> Self {
        Self { config }
    }

    /// 获取单个用户信息
    pub fn get(&self) -> GetUserBuilder {
        GetUserBuilder {
            config: self.config.clone(),
            user_id: String::new(),
        }
    }

    /// 获取用户列表
    pub fn list(&self) -> ListUsersBuilder {
        ListUsersBuilder {
            config: self.config.clone(),
            page_size: Some(20),
            page_token: None,
            department_id: None,
            status: None,
        }
    }

    /// 修改用户部分信息
    pub fn patch(&self) -> PatchUserBuilder {
        PatchUserBuilder {
            config: self.config.clone(),
            user_id: String::new(),
            name: None,
            email: None,
            mobile: None,
            department_ids: None,
            status: None,
            rule_ids: None,
        }
    }
}

/// 获取单个用户信息构建器
#[derive(Debug)]
pub struct GetUserBuilder {
    config: Arc<crate::models::SecurityConfig>,
    user_id: String,
}

impl GetUserBuilder {
    /// 设置用户ID
    pub fn user_id(mut self, user_id: impl Into<String>) -> Self {
        self.user_id = user_id.into();
        self
    }

    /// 发送请求获取用户信息
    pub async fn send(self) -> crate::SecurityResult<crate::models::acs::UserInfo> {
        let url = format!(
            "{}/open-apis/acs/v1/users/{}",
            self.config.base_url, self.user_id
        );

        let response = reqwest::Client::new()
            .get(&url)
            .header(
                "Authorization",
                format!("Bearer {}", get_app_token(&self.config).await?),
            )
            .header("Content-Type", "application/json")
            .send()
            .await?;

        if response.status().is_success() {
            let api_response: crate::models::ApiResponse<crate::models::acs::UserInfo> =
                response.json().await?;
            match api_response.data {
                Some(user) => Ok(user),
                None => Err(api_error(
                    api_response.code as u16,
                    "/acs/v1/users",
                    &api_response.msg,
                    None,
                )),
            }
        } else {
            Err(api_error(
                response.status().as_u16(),
                "/acs/v1/users",
                format!("HTTP: {}", response.status()),
                None,
            ))
        }
    }
}

/// 获取用户列表构建器
#[derive(Debug)]
pub struct ListUsersBuilder {
    config: Arc<crate::models::SecurityConfig>,
    page_size: Option<i32>,
    page_token: Option<String>,
    department_id: Option<String>,
    status: Option<crate::models::Status>,
}

impl ListUsersBuilder {
    /// 设置页面大小
    pub fn page_size(mut self, page_size: i32) -> Self {
        self.page_size = Some(page_size);
        self
    }

    /// 设置分页标记
    pub fn page_token(mut self, page_token: impl Into<String>) -> Self {
        self.page_token = Some(page_token.into());
        self
    }

    /// 设置部门ID过滤
    pub fn department_id(mut self, department_id: impl Into<String>) -> Self {
        self.department_id = Some(department_id.into());
        self
    }

    /// 设置状态过滤
    pub fn status(mut self, status: crate::models::Status) -> Self {
        self.status = Some(status);
        self
    }

    /// 发送请求获取用户列表
    pub async fn send(self) -> crate::SecurityResult<crate::models::acs::UserListResponse> {
        let mut url = format!("{}/open-apis/acs/v1/users", self.config.base_url);
        let mut query_params = Vec::new();

        if let Some(page_size) = self.page_size {
            query_params.push(format!("page_size={page_size}"));
        }
        if let Some(page_token) = &self.page_token {
            query_params.push(format!("page_token={page_token}"));
        }
        if let Some(department_id) = &self.department_id {
            query_params.push(format!("department_id={department_id}"));
        }
        if let Some(status) = &self.status {
            query_params.push(format!(
                "status={}",
                serde_json::to_string(status).unwrap_or_default()
            ));
        }

        if !query_params.is_empty() {
            url.push_str(&format!("?{}", query_params.join("&")));
        }

        let response = reqwest::Client::new()
            .get(&url)
            .header(
                "Authorization",
                format!("Bearer {}", get_app_token(&self.config).await?),
            )
            .header("Content-Type", "application/json")
            .send()
            .await?;

        if response.status().is_success() {
            let api_response: crate::models::ApiResponse<crate::models::acs::UserListResponse> =
                response.json().await?;
            match api_response.data {
                Some(users) => Ok(users),
                None => Err(api_error(
                    api_response.code as u16,
                    "/acs/v1/users",
                    &api_response.msg,
                    None,
                )),
            }
        } else {
            Err(api_error(
                response.status().as_u16(),
                "/acs/v1/users",
                format!("HTTP: {}", response.status()),
                None,
            ))
        }
    }
}

/// 修改用户信息构建器
#[derive(Debug)]
pub struct PatchUserBuilder {
    config: Arc<crate::models::SecurityConfig>,
    user_id: String,
    name: Option<String>,
    email: Option<String>,
    mobile: Option<String>,
    department_ids: Option<Vec<String>>,
    status: Option<crate::models::Status>,
    rule_ids: Option<Vec<String>>,
}

impl PatchUserBuilder {
    /// 设置用户ID
    pub fn user_id(mut self, user_id: impl Into<String>) -> Self {
        self.user_id = user_id.into();
        self
    }

    /// 设置用户姓名
    pub fn name(mut self, name: impl Into<String>) -> Self {
        self.name = Some(name.into());
        self
    }

    /// 设置用户邮箱
    pub fn email(mut self, email: impl Into<String>) -> Self {
        self.email = Some(email.into());
        self
    }

    /// 设置用户手机号
    pub fn mobile(mut self, mobile: impl Into<String>) -> Self {
        self.mobile = Some(mobile.into());
        self
    }

    /// 设置部门ID列表
    pub fn department_ids(mut self, department_ids: Vec<String>) -> Self {
        self.department_ids = Some(department_ids);
        self
    }

    /// 设置用户状态
    pub fn status(mut self, status: crate::models::Status) -> Self {
        self.status = Some(status);
        self
    }

    /// 设置权限组ID列表
    pub fn rule_ids(mut self, rule_ids: Vec<String>) -> Self {
        self.rule_ids = Some(rule_ids);
        self
    }

    /// 发送请求修改用户信息
    pub async fn send(self) -> crate::SecurityResult<crate::models::acs::UserInfo> {
        let url = format!(
            "{}/open-apis/acs/v1/users/{}",
            self.config.base_url, self.user_id
        );

        let mut request_body = serde_json::Map::new();

        if let Some(name) = self.name {
            request_body.insert("name".to_string(), serde_json::Value::String(name));
        }
        if let Some(email) = self.email {
            request_body.insert("email".to_string(), serde_json::Value::String(email));
        }
        if let Some(mobile) = self.mobile {
            request_body.insert("mobile".to_string(), serde_json::Value::String(mobile));
        }
        if let Some(department_ids) = self.department_ids {
            request_body.insert(
                "department_ids".to_string(),
                serde_json::Value::Array(
                    department_ids
                        .into_iter()
                        .map(serde_json::Value::String)
                        .collect(),
                ),
            );
        }
        if let Some(status) = self.status {
            request_body.insert(
                "status".to_string(),
                serde_json::to_value(status).unwrap_or(serde_json::Value::Null),
            );
        }
        if let Some(rule_ids) = self.rule_ids {
            request_body.insert(
                "rule_ids".to_string(),
                serde_json::Value::Array(
                    rule_ids
                        .into_iter()
                        .map(serde_json::Value::String)
                        .collect(),
                ),
            );
        }

        let response = reqwest::Client::new()
            .patch(&url)
            .header(
                "Authorization",
                format!("Bearer {}", get_app_token(&self.config).await?),
            )
            .header("Content-Type", "application/json")
            .json(&request_body)
            .send()
            .await?;

        if response.status().is_success() {
            let api_response: crate::models::ApiResponse<crate::models::acs::UserInfo> =
                response.json().await?;
            match api_response.data {
                Some(user) => Ok(user),
                None => Err(api_error(
                    api_response.code as u16,
                    "/acs/v1/users",
                    &api_response.msg,
                    None,
                )),
            }
        } else {
            Err(api_error(
                response.status().as_u16(),
                "/acs/v1/users",
                format!("HTTP: {}", response.status()),
                None,
            ))
        }
    }
}

/// 获取应用访问令牌的辅助函数
async fn get_app_token(config: &crate::models::SecurityConfig) -> crate::SecurityResult<String> {
    // 使用 SecurityConfig 的 get_app_access_token 方法获取真实的 token
    config.get_app_access_token().await
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::Arc;

    fn create_test_config() -> Arc<crate::models::SecurityConfig> {
        Arc::new(crate::models::SecurityConfig {
            app_id: "test_app_id".to_string(),
            app_secret: "test_app_secret".to_string(),
            base_url: "https://open.feishu.cn".to_string(),
        })
    }

    #[test]
    fn test_users_service_creation() {
        let config = create_test_config();
        let service = UsersService::new(config.clone());
        assert_eq!(service.config.app_id, "test_app_id");
    }

    #[test]
    fn test_get_user_builder() {
        let config = create_test_config();
        let service = UsersService::new(config);
        let builder = service.get().user_id("user_123");
        assert_eq!(builder.user_id, "user_123");
    }

    #[test]
    fn test_list_users_builder_defaults() {
        let config = create_test_config();
        let service = UsersService::new(config);
        let builder = service.list();
        assert_eq!(builder.page_size, Some(20));
        assert_eq!(builder.page_token, None);
        assert_eq!(builder.department_id, None);
        assert_eq!(builder.status, None);
    }

    #[test]
    fn test_list_users_builder_with_params() {
        let config = create_test_config();
        let service = UsersService::new(config);
        let builder = service
            .list()
            .page_size(50)
            .page_token("token_123")
            .department_id("dept_456")
            .status(crate::models::Status::Active);

        assert_eq!(builder.page_size, Some(50));
        assert_eq!(builder.page_token, Some("token_123".to_string()));
        assert_eq!(builder.department_id, Some("dept_456".to_string()));
        assert!(builder.status.is_some());
    }

    #[test]
    fn test_patch_user_builder() {
        let config = create_test_config();
        let service = UsersService::new(config);
        let builder = service
            .patch()
            .user_id("user_789")
            .name("张三")
            .email("zhangsan@example.com")
            .mobile("13800138000")
            .department_ids(vec!["dept_1".to_string(), "dept_2".to_string()])
            .status(crate::models::Status::Active)
            .rule_ids(vec!["rule_1".to_string()]);

        assert_eq!(builder.user_id, "user_789");
        assert_eq!(builder.name, Some("张三".to_string()));
        assert_eq!(builder.email, Some("zhangsan@example.com".to_string()));
        assert_eq!(builder.mobile, Some("13800138000".to_string()));
        assert_eq!(
            builder.department_ids,
            Some(vec!["dept_1".to_string(), "dept_2".to_string()])
        );
        assert!(builder.status.is_some());
        assert_eq!(builder.rule_ids, Some(vec!["rule_1".to_string()]));
    }

    #[test]
    fn test_patch_user_builder_chaining() {
        let config = create_test_config();
        let service = UsersService::new(config);
        let builder = service
            .patch()
            .user_id("user_123")
            .name("李四")
            .email("lisi@example.com");

        assert_eq!(builder.user_id, "user_123");
        assert_eq!(builder.name, Some("李四".to_string()));
        assert_eq!(builder.email, Some("lisi@example.com".to_string()));
        assert!(builder.mobile.is_none()); // 未设置的字段应保持 None
    }
}