gcp_vertex_ai_generative_language/
auth.rs

1//! Authentication related code.
2
3use std::str::FromStr;
4
5use tonic::Request;
6
7use crate::{Credentials, Error};
8
9/// API Key authorization
10#[derive(Clone)]
11pub struct APIKey {
12    api_key: String,
13}
14
15/// Authentication interceptor
16#[derive(Clone)]
17pub enum Authentication {
18    /// API Key authentication
19    APIKey(APIKey),
20    /// No authentication
21    None,
22}
23
24impl Authentication {
25    /// Build an authentication interceptor from the given credentials
26    pub async fn build(credentials: Credentials) -> Result<Authentication, Error> {
27        match credentials {
28            Credentials::ApiKey(api_key) => {
29                let authz = APIKey { api_key };
30
31                Ok(Authentication::APIKey(authz))
32            }
33            Credentials::None => Ok(Authentication::None),
34        }
35    }
36}
37
38impl tonic::service::Interceptor for Authentication {
39    fn call(&mut self, mut req: Request<()>) -> Result<Request<()>, tonic::Status> {
40        match self {
41            Authentication::APIKey(api_key_auth) => {
42                let api_key = api_key_auth.api_key.clone();
43                let api_key = FromStr::from_str(&api_key).unwrap();
44                req.metadata_mut().insert("x-goog-api-key", api_key);
45                Ok(req)
46            }
47            Authentication::None => Ok(req),
48        }
49    }
50}