authr_http 0.1.0

Actix Web integration for authr.
Documentation
use actix_web::{HttpMessage, HttpRequest, HttpResponse, Responder, web};
use serde::Deserialize;
use serde_json::json;

use authr_core::{context::AuthrContext, database::AuthDatabase};
use authr_operations::account::{
    AccountInfoInput, GetAccessTokenInput, LinkSocialAccountInput, ListAccountsInput,
    RefreshTokenInput, UnlinkAccountInput, account_info as account_info_operation,
    get_access_token as get_access_token_operation,
    link_social_account as link_social_account_operation, list_accounts as list_accounts_operation,
    refresh_token as refresh_token_operation, unlink_account as unlink_account_operation,
};

use crate::{
    error::ServerError, middleware::session::AuthenticatedSession, utils::get_provider_callback_url,
};

// -------------------- List Accounts - GET "/list-accounts" --------------------

#[tracing::instrument(name = "auth.list_accounts", skip_all, err)]
pub async fn list_accounts<D: AuthDatabase + 'static>(
    req: HttpRequest,
    ctx: web::Data<AuthrContext<D>>,
) -> Result<impl Responder, ServerError> {
    let authenticated = get_authenticated_session(&req)?;

    let result = list_accounts_operation(
        ctx.get_ref(),
        ListAccountsInput {
            user_id: authenticated.user.id,
        },
    )
    .await?;

    Ok(HttpResponse::Ok().json(json!({
        "accounts": result.accounts.iter().map(|account| json!({
            "id": account.id,
            "providerId": account.provider_id,
            "accountId": account.account_id,
            "userId": account.user_id,
            "scopes": account.scopes,
            "createdAt": account.created_at,
            "updatedAt": account.updated_at,
        })).collect::<Vec<_>>()
    })))
}

// -------------------- Link Social Account - POST "/link-social" --------------------

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct LinkSocialAccountRequest {
    /// ID of the configured OAuth provider.
    pub provider: String,

    /// Application URL to redirect to after successfully linking the account.
    pub callback_url: Option<String>,

    /// Return the authorization URL without redirecting.
    #[serde(default)]
    pub disable_redirect: bool,

    /// Override the provider's default OAuth scopes.
    pub scopes: Option<Vec<String>>,
}

#[tracing::instrument(
    name = "auth.link_social_account",
    skip_all,
    fields(
        provider = %body.provider,
        disable_redirect = body.disable_redirect,
        has_callback_url = body.callback_url.is_some(),
        has_custom_scopes = body.scopes.is_some()
    ),
    err
)]
pub async fn link_social_account<D: AuthDatabase + 'static>(
    req: HttpRequest,
    ctx: web::Data<AuthrContext<D>>,
    body: web::Json<LinkSocialAccountRequest>,
) -> Result<HttpResponse, ServerError> {
    let authenticated = get_authenticated_session(&req)?;

    // ----- Validate callback URL
    if let Some(callback_url) = body.callback_url.as_deref() {
        if !ctx.config().base_url.is_allowed(callback_url) {
            return Err(ServerError::InvalidCallbackUrl);
        }
    }

    // ----- Build provider callback URL
    let redirect_uri = get_provider_callback_url(
        &ctx.config().base_url,
        &ctx.config().base_path,
        &req,
        &body.provider,
    )?;

    // ----- Initiate account linking
    let result = link_social_account_operation(
        ctx.get_ref(),
        LinkSocialAccountInput {
            user_id: authenticated.user.id,
            session_id: authenticated.session.id,
            provider_id: body.provider.clone(),
            redirect_uri,
            callback_url: body.callback_url.clone(),
            scopes: body.scopes.clone(),
        },
    )
    .await?;

    // ----- Return authorization URL
    if body.disable_redirect {
        Ok(HttpResponse::Ok().json(serde_json::json!({
            "url": result.authorization_url
        })))
    } else {
        Ok(HttpResponse::Found()
            .append_header(("Location", result.authorization_url.as_str()))
            .finish())
    }
}

// -------------------- Unlink Account - POST "/unlink-account" --------------------

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct UnlinkAccountRequest {
    pub account_id: String,
}

#[tracing::instrument(name = "auth.unlink_account", skip_all, err)]
pub async fn unlink_account<D: AuthDatabase + 'static>(
    req: HttpRequest,
    ctx: web::Data<AuthrContext<D>>,
    body: web::Json<UnlinkAccountRequest>,
) -> Result<impl Responder, ServerError> {
    let authenticated = get_authenticated_session(&req)?;

    let result = unlink_account_operation(
        ctx.get_ref(),
        UnlinkAccountInput {
            user_id: authenticated.user.id,
            account_id: body.account_id.clone(),
        },
    )
    .await?;

    Ok(HttpResponse::Ok().json(json!({
        "success": result.success
    })))
}

// -------------------- Get Access Token - POST "/get-access-token" --------------------

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct AccountTokenRequest {
    pub account_id: String,
}

#[tracing::instrument(name = "auth.get_access_token", skip_all, err)]
pub async fn get_access_token<D: AuthDatabase + 'static>(
    req: HttpRequest,
    ctx: web::Data<AuthrContext<D>>,
    body: web::Json<AccountTokenRequest>,
) -> Result<impl Responder, ServerError> {
    let authenticated = get_authenticated_session(&req)?;

    let result = get_access_token_operation(
        ctx.get_ref(),
        GetAccessTokenInput {
            user_id: authenticated.user.id,
            account_id: body.account_id.clone(),
        },
    )
    .await?;

    Ok(HttpResponse::Ok().json(json!({
        "accessToken": result.access_token,
        "accessTokenExpiresAt": result.access_token_expires_at,
        "idToken": result.id_token,
        "scopes": result.scopes,
    })))
}

// -------------------- Refresh Token - POST "/refresh-token" --------------------

#[tracing::instrument(name = "auth.refresh_token", skip_all, err)]
pub async fn refresh_token<D: AuthDatabase + 'static>(
    req: HttpRequest,
    ctx: web::Data<AuthrContext<D>>,
    body: web::Json<AccountTokenRequest>,
) -> Result<impl Responder, ServerError> {
    let authenticated = get_authenticated_session(&req)?;

    let result = refresh_token_operation(
        ctx.get_ref(),
        RefreshTokenInput {
            user_id: authenticated.user.id,
            account_id: body.account_id.clone(),
        },
    )
    .await?;

    Ok(HttpResponse::Ok().json(json!({
        "accessToken": result.access_token,
        "refreshToken": result.refresh_token,
        "accessTokenExpiresAt": result.access_token_expires_at,
        "scopes": result.scopes,
    })))
}

// -------------------- Account Info - GET "/account-info" --------------------

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct AccountInfoQuery {
    pub account_id: String,
}

#[tracing::instrument(name = "auth.account_info", skip_all, err)]
pub async fn account_info<D: AuthDatabase + 'static>(
    req: HttpRequest,
    ctx: web::Data<AuthrContext<D>>,
    query: web::Query<AccountInfoQuery>,
) -> Result<impl Responder, ServerError> {
    let authenticated = get_authenticated_session(&req)?;

    let result = account_info_operation(
        ctx.get_ref(),
        AccountInfoInput {
            user_id: authenticated.user.id,
            account_id: query.account_id.clone(),
        },
    )
    .await?;

    Ok(HttpResponse::Ok().json(json!({
        "id": result.id,
        "name": result.name,
        "email": result.email,
        "image": result.image,
        "emailVerified": result.email_verified,
    })))
}

// -------------------- Helpers --------------------

/// Retrieves the authenticated session attached by the session middleware.
fn get_authenticated_session(req: &HttpRequest) -> Result<AuthenticatedSession, ServerError> {
    req.extensions()
        .get::<AuthenticatedSession>()
        .cloned()
        .ok_or(ServerError::Internal)
}