lib_client_openai/
auth.rs

1//! Authentication strategies for the OpenAI API.
2
3use crate::error::Result;
4use async_trait::async_trait;
5use reqwest::header::HeaderMap;
6
7/// Authentication strategy trait.
8#[async_trait]
9pub trait AuthStrategy: Send + Sync {
10    /// Apply authentication to the request headers.
11    async fn apply(&self, headers: &mut HeaderMap) -> Result<()>;
12}
13
14/// API key authentication (Bearer token).
15#[derive(Debug, Clone)]
16pub struct ApiKeyAuth {
17    api_key: String,
18    organization: Option<String>,
19}
20
21impl ApiKeyAuth {
22    /// Create a new API key authentication strategy.
23    pub fn new(api_key: impl Into<String>) -> Self {
24        Self {
25            api_key: api_key.into(),
26            organization: None,
27        }
28    }
29
30    /// Set the organization ID.
31    pub fn with_organization(mut self, org: impl Into<String>) -> Self {
32        self.organization = Some(org.into());
33        self
34    }
35}
36
37#[async_trait]
38impl AuthStrategy for ApiKeyAuth {
39    async fn apply(&self, headers: &mut HeaderMap) -> Result<()> {
40        let auth_value = format!("Bearer {}", self.api_key);
41        headers.insert("Authorization", auth_value.parse().unwrap());
42
43        if let Some(org) = &self.organization {
44            headers.insert("OpenAI-Organization", org.parse().unwrap());
45        }
46
47        Ok(())
48    }
49}