use chrono::{Duration, Utc};
use super::idtoken::{OidcIdInfo, verify_idtoken_with_algorithm};
use super::utils::{generate_store_token, verify_and_consume_nonce};
use crate::oauth2::OAuth2Error;
use crate::oauth2::provider::ProviderConfig;
use crate::oauth2::types::{FedCMNonceResponse, TokenType};
const FEDCM_NONCE_TTL: u64 = 120;
pub async fn prepare_fedcm_nonce() -> Result<FedCMNonceResponse, OAuth2Error> {
let expires_at = Utc::now() + Duration::seconds(FEDCM_NONCE_TTL as i64);
let (nonce_token, nonce_id) =
generate_store_token(TokenType::Nonce, FEDCM_NONCE_TTL, expires_at, None).await?;
Ok(FedCMNonceResponse {
nonce: nonce_token,
nonce_id,
})
}
pub(crate) async fn validate_fedcm_token(
ctx: &ProviderConfig,
token: &str,
nonce_id: &str,
) -> Result<OidcIdInfo, OAuth2Error> {
let (idinfo, _algorithm) = verify_idtoken_with_algorithm(ctx, token.to_string())
.await
.map_err(|e| OAuth2Error::IdToken(e.to_string()))?;
verify_and_consume_nonce(nonce_id, idinfo.nonce.as_deref()).await?;
Ok(idinfo)
}