1use reqwest::header::{HeaderValue, HeaderMap};
2use crate::types::errors::{AnthropicError, Result};
3
4#[derive(Debug, Clone)]
6pub enum AuthMethod {
7 Anthropic,
9 Bearer,
11 Token,
13}
14
15#[derive(Debug, Clone)]
17pub struct AuthHandler {
18 api_key: String,
19 auth_method: AuthMethod,
20}
21
22impl AuthHandler {
23 pub fn new(api_key: String) -> Self {
25 Self {
26 api_key,
27 auth_method: AuthMethod::Anthropic,
28 }
29 }
30
31 pub fn new_bearer(api_key: String) -> Self {
33 Self {
34 api_key,
35 auth_method: AuthMethod::Bearer,
36 }
37 }
38
39 pub fn new_token(api_key: String) -> Self {
41 Self {
42 api_key,
43 auth_method: AuthMethod::Token,
44 }
45 }
46
47 pub fn with_method(api_key: String, auth_method: AuthMethod) -> Self {
49 Self {
50 api_key,
51 auth_method,
52 }
53 }
54
55 pub fn add_auth_headers(&self, headers: &mut HeaderMap) -> Result<()> {
57 match self.auth_method {
58 AuthMethod::Anthropic => {
59 let api_key_header = HeaderValue::from_str(&self.api_key)
60 .map_err(|_| AnthropicError::Configuration {
61 message: "Invalid API key format".to_string(),
62 })?;
63
64 headers.insert("x-api-key", api_key_header);
65 headers.insert("anthropic-version", HeaderValue::from_static("2023-06-01"));
66 }
67 AuthMethod::Bearer => {
68 let bearer_token = format!("Bearer {}", self.api_key);
69 let auth_header = HeaderValue::from_str(&bearer_token)
70 .map_err(|_| AnthropicError::Configuration {
71 message: "Invalid API key format for Bearer token".to_string(),
72 })?;
73
74 headers.insert("authorization", auth_header);
75 headers.insert("anthropic-version", HeaderValue::from_static("2023-06-01"));
76 }
77 AuthMethod::Token => {
78 let token_header = HeaderValue::from_str(&self.api_key)
79 .map_err(|_| AnthropicError::Configuration {
80 message: "Invalid API key format for token header".to_string(),
81 })?;
82
83 headers.insert("token", token_header);
84 headers.insert("anthropic-version", HeaderValue::from_static("2023-06-01"));
85 }
86 }
87
88 headers.insert("content-type", HeaderValue::from_static("application/json"));
89
90 Ok(())
91 }
92}