Skip to main content

authr_http/utils/
oauth.rs

1use actix_web::HttpRequest;
2use url::Url;
3
4use authr_core::{
5    config::BaseUrl, context::AuthrContext, database::AuthDatabase, error::AuthrCoreError,
6};
7use authr_oauth::OAuthTransaction;
8
9use crate::error::ServerError;
10
11/// Builds the OAuth callback URL for the specified provider.
12pub fn get_provider_callback_url(
13    base_url: &BaseUrl,
14    base_path: &str,
15    req: &HttpRequest,
16    provider_id: &str,
17) -> Result<Url, ServerError> {
18    // ----- Resolve base URL
19    let connection = req.connection_info();
20
21    let mut url = base_url
22        .resolve(Some(connection.host()), Some(connection.scheme()))
23        .map_err(|_| ServerError::Internal)?;
24
25    // ----- Append callback path
26    {
27        let mut segments = url.path_segments_mut().map_err(|_| ServerError::Internal)?;
28
29        segments.pop_if_empty();
30
31        segments.extend(base_path.split('/').filter(|segment| !segment.is_empty()));
32
33        segments.push("callback");
34        segments.push(provider_id);
35    }
36
37    Ok(url)
38}
39
40// -------------------- Callback Flow --------------------
41
42#[derive(Debug, Clone, Copy, PartialEq, Eq)]
43pub enum OAuthCallbackFlow {
44    SignIn,
45    LinkAccount,
46}
47
48pub async fn identify_oauth_callback<D>(
49    ctx: &AuthrContext<D>,
50    state: &str,
51) -> Result<OAuthCallbackFlow, AuthrCoreError>
52where
53    D: AuthDatabase + 'static,
54{
55    let identifier = format!("oauth:{state}");
56
57    let verification = ctx
58        .store()
59        .find_verification_by_identifier(&identifier)
60        .await?
61        .ok_or(AuthrCoreError::InvalidVerificationToken)?;
62
63    let transaction: OAuthTransaction = serde_json::from_str(&verification.value)
64        .map_err(|_| AuthrCoreError::InvalidVerificationToken)?;
65
66    if verification.expires_at <= chrono::Utc::now() {
67        return Err(AuthrCoreError::InvalidVerificationToken);
68    }
69
70    Ok(if transaction.link.is_some() {
71        OAuthCallbackFlow::LinkAccount
72    } else {
73        OAuthCallbackFlow::SignIn
74    })
75}