use std::future::Future;
use std::sync::Arc;
use tonic::Code;
use tonic::service::interceptor::InterceptedService;
use tonic::transport::Channel;
use uuid::Uuid;
use crate::AxiamError;
use crate::grpc::client::{RefreshFn, status_to_axiam_error};
use crate::grpc::r#gen::user_info_service_client::UserInfoServiceClient;
use crate::grpc::r#gen::{GetUserInfoRequest, GetUserInfoResponse as WireGetUserInfoResponse};
use crate::grpc::interceptor::AuthInterceptor;
use crate::token::TokenManager;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UserInfo {
pub sub: String,
pub tenant_id: String,
pub org_id: String,
pub email: Option<String>,
pub preferred_username: Option<String>,
}
impl From<WireGetUserInfoResponse> for UserInfo {
fn from(wire: WireGetUserInfoResponse) -> Self {
UserInfo {
sub: wire.sub,
tenant_id: wire.tenant_id,
org_id: wire.org_id,
email: wire.email,
preferred_username: wire.preferred_username,
}
}
}
type InnerClient = UserInfoServiceClient<InterceptedService<Channel, AuthInterceptor>>;
#[derive(Clone)]
pub struct UserInfoGrpcClient {
inner: InnerClient,
token_manager: Arc<TokenManager>,
tenant_id: Uuid,
refresh_fn: RefreshFn,
}
impl UserInfoGrpcClient {
pub fn new(
channel: Channel,
token_manager: Arc<TokenManager>,
tenant_id: Uuid,
refresh_fn: RefreshFn,
) -> Self {
let interceptor = AuthInterceptor::new(Arc::clone(&token_manager), tenant_id);
let inner = UserInfoServiceClient::with_interceptor(channel, interceptor);
Self {
inner,
token_manager,
tenant_id,
refresh_fn,
}
}
pub fn tenant_id(&self) -> Uuid {
self.tenant_id
}
pub async fn get_user_info(&self) -> Result<UserInfo, AxiamError> {
match self.try_get_user_info().await {
Ok(resp) => Ok(resp.into()),
Err(status) if status.code() == Code::Unauthenticated => self
.refresh_and_retry(status, || self.try_get_user_info())
.await
.map(Into::into),
Err(status) => Err(status_to_axiam_error(status)),
}
}
async fn try_get_user_info(&self) -> Result<WireGetUserInfoResponse, tonic::Status> {
let mut client = self.inner.clone();
client
.get_user_info(GetUserInfoRequest {})
.await
.map(|resp| resp.into_inner())
}
async fn refresh_and_retry<T, F, Fut>(
&self,
original: tonic::Status,
attempt: F,
) -> Result<T, AxiamError>
where
F: Fn() -> Fut,
Fut: Future<Output = Result<T, tonic::Status>>,
{
if !self.token_manager.has_refresh_token().await {
return Err(status_to_axiam_error(original));
}
let observed = self
.token_manager
.cached_access_token()
.map(|t| t.expose().clone())
.unwrap_or_default();
let refresh_fn = Arc::clone(&self.refresh_fn);
self.token_manager
.refresh_if_needed(&observed, move |refresh_token| refresh_fn(refresh_token))
.await?;
attempt().await.map_err(status_to_axiam_error)
}
}