use anapaya_aa_protobuf::v1::{AuthenticateByKeyRequest, AuthenticateByKeyResponse, Metadata};
use scion_sdk_reqwest_connect_rpc::client::{CrpcClient, CrpcClientError};
pub const ANAPAYA_AA_V1: &str = "anapaya.aa.v1";
pub const AUTH_SERVICE: &str = "AuthService";
pub const AUTHENTICATE_BY_KEY: &str = "/AuthenticateByKey";
pub struct AuthResult {
pub snap_token: String,
pub metadata: Option<Metadata>,
}
#[cfg_attr(test, mockall::automock)]
#[async_trait::async_trait]
pub trait AaAuthClient: Send + Sync {
async fn authenticate_by_key(
&self,
api_key: String,
device_id: String,
requested_validity: i32,
) -> Result<AuthResult, CrpcClientError>;
}
pub struct CrpcAaAuthClient {
client: CrpcClient,
}
impl CrpcAaAuthClient {
pub fn new(base_url: &url::Url) -> anyhow::Result<Self> {
Ok(Self {
client: CrpcClient::new(base_url)?,
})
}
pub fn new_with_client(base_url: &url::Url, client: reqwest::Client) -> anyhow::Result<Self> {
Ok(Self {
client: CrpcClient::new_with_client(base_url, client)?,
})
}
}
#[async_trait::async_trait]
impl AaAuthClient for CrpcAaAuthClient {
async fn authenticate_by_key(
&self,
api_key: String,
device_id: String,
requested_validity: i32,
) -> Result<AuthResult, CrpcClientError> {
let resp = self
.client
.unary_request::<AuthenticateByKeyRequest, AuthenticateByKeyResponse>(
&format!("{ANAPAYA_AA_V1}.{AUTH_SERVICE}{AUTHENTICATE_BY_KEY}"),
AuthenticateByKeyRequest {
api_key,
device_id,
requested_validity,
},
)
.await?;
Ok(AuthResult {
snap_token: resp.snap_token,
metadata: resp.metadata,
})
}
}