open_lark/core/request_builder/
auth_handler.rs1use crate::core::{
2 config::Config, constants::AccessTokenType, error::LarkAPIError, req_option::RequestOption,
3};
4use reqwest::RequestBuilder;
5
6pub struct AuthHandler;
8
9impl AuthHandler {
10 pub async fn apply_auth(
12 req_builder: RequestBuilder,
13 access_token_type: AccessTokenType,
14 config: &Config,
15 option: &RequestOption,
16 ) -> Result<RequestBuilder, LarkAPIError> {
17 match access_token_type {
18 AccessTokenType::None => Ok(req_builder),
19 AccessTokenType::App => Self::apply_app_auth(req_builder, config, option).await,
20 AccessTokenType::Tenant => Self::apply_tenant_auth(req_builder, config, option).await,
21 AccessTokenType::User => Ok(Self::apply_user_auth(req_builder, option)),
22 }
23 }
24
25 async fn apply_app_auth(
27 req_builder: RequestBuilder,
28 config: &Config,
29 option: &RequestOption,
30 ) -> Result<RequestBuilder, LarkAPIError> {
31 let app_access_token = if !option.app_access_token.is_empty() {
32 option.app_access_token.clone()
33 } else if config.enable_token_cache {
34 let token_manager = config.token_manager.lock().await;
35 token_manager
36 .get_app_access_token(config, &option.app_ticket, &config.app_ticket_manager)
37 .await?
38 } else {
39 return Err(LarkAPIError::MissingAccessToken);
40 };
41
42 Ok(Self::add_auth_header(req_builder, &app_access_token))
43 }
44
45 async fn apply_tenant_auth(
47 req_builder: RequestBuilder,
48 config: &Config,
49 option: &RequestOption,
50 ) -> Result<RequestBuilder, LarkAPIError> {
51 let tenant_access_token = if !option.tenant_access_token.is_empty() {
52 option.tenant_access_token.clone()
53 } else if config.enable_token_cache {
54 let token_manager = config.token_manager.lock().await;
55 token_manager
56 .get_tenant_access_token(
57 config,
58 &option.tenant_key,
59 &option.app_ticket,
60 &config.app_ticket_manager,
61 )
62 .await?
63 } else {
64 return Err(LarkAPIError::MissingAccessToken);
65 };
66
67 Ok(Self::add_auth_header(req_builder, &tenant_access_token))
68 }
69
70 fn apply_user_auth(req_builder: RequestBuilder, option: &RequestOption) -> RequestBuilder {
72 Self::add_auth_header(req_builder, &option.user_access_token)
73 }
74
75 fn add_auth_header(req_builder: RequestBuilder, token: &str) -> RequestBuilder {
77 req_builder.header("Authorization", format!("Bearer {token}"))
78 }
79}