use actix_web::HttpRequest;
use url::Url;
use authr_core::{
config::BaseUrl, context::AuthrContext, database::AuthDatabase, error::AuthrCoreError,
};
use authr_oauth::OAuthTransaction;
use crate::error::ServerError;
pub fn get_provider_callback_url(
base_url: &BaseUrl,
base_path: &str,
req: &HttpRequest,
provider_id: &str,
) -> Result<Url, ServerError> {
let connection = req.connection_info();
let mut url = base_url
.resolve(Some(connection.host()), Some(connection.scheme()))
.map_err(|_| ServerError::Internal)?;
{
let mut segments = url.path_segments_mut().map_err(|_| ServerError::Internal)?;
segments.pop_if_empty();
segments.extend(base_path.split('/').filter(|segment| !segment.is_empty()));
segments.push("callback");
segments.push(provider_id);
}
Ok(url)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OAuthCallbackFlow {
SignIn,
LinkAccount,
}
pub async fn identify_oauth_callback<D>(
ctx: &AuthrContext<D>,
state: &str,
) -> Result<OAuthCallbackFlow, AuthrCoreError>
where
D: AuthDatabase + 'static,
{
let identifier = format!("oauth:{state}");
let verification = ctx
.store()
.find_verification_by_identifier(&identifier)
.await?
.ok_or(AuthrCoreError::InvalidVerificationToken)?;
let transaction: OAuthTransaction = serde_json::from_str(&verification.value)
.map_err(|_| AuthrCoreError::InvalidVerificationToken)?;
if verification.expires_at <= chrono::Utc::now() {
return Err(AuthrCoreError::InvalidVerificationToken);
}
Ok(if transaction.link.is_some() {
OAuthCallbackFlow::LinkAccount
} else {
OAuthCallbackFlow::SignIn
})
}