openai_ng/
auth.rs

1use crate::error::*;
2use async_trait::async_trait;
3use http::header::{self, HeaderValue};
4use reqwest::Request;
5use tracing::*;
6
7/// trait to authorize `reqwest::Request`, might add more authorization method in the future
8#[async_trait]
9pub trait AuthenticatorTrait {
10    async fn authorize(&self, req: &mut Request) -> Result<()>;
11}
12
13/// Bearer token authorization
14#[derive(Debug, Clone)]
15pub struct Bearer {
16    key: String,
17}
18
19impl Bearer {
20    /// create a new Bearer token authorization
21    pub fn new(key: String) -> Self {
22        Self { key }
23    }
24}
25
26#[async_trait]
27impl AuthenticatorTrait for Bearer {
28    async fn authorize(&self, req: &mut Request) -> Result<()> {
29        let k = header::AUTHORIZATION;
30        let v = HeaderValue::from_str(&format!("Bearer {}", self.key))?;
31        if let Some(k) = req.headers_mut().insert(k, v) {
32            warn!("auth header {:?} exists and overwroted", k);
33        }
34        Ok(())
35    }
36}