authr_http 0.1.0

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

use authr_core::{context::AuthrContext, database::AuthDatabase};
use authr_operations::password::{
    ChangePasswordInput, SetPasswordInput, VerifyPasswordInput,
    change_password as change_password_operation, set_password as set_password_operation,
    verify_password as verify_password_operation,
};

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

// -------------------- Requests --------------------

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct VerifyPasswordRequest {
    /// Current password to verify.
    pub password: String,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct ChangePasswordRequest {
    /// New password to set.
    pub new_password: String,

    /// Current password of the user.
    pub current_password: String,

    /// Whether to revoke all sessions except the current one.
    #[serde(default)]
    pub revoke_other_sessions: bool,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct SetPasswordRequest {
    /// New password to set.
    pub new_password: String,
}

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

fn get_authenticated_session(req: &HttpRequest) -> Result<AuthenticatedSession, ServerError> {
    req.extensions()
        .get::<AuthenticatedSession>()
        .cloned()
        .ok_or(ServerError::InvalidCredentials)
}

// -------------------- Verify Password --------------------

#[tracing::instrument(name = "auth.verify_password", skip_all)]
/// Verifies the authenticated user's current password.
pub async fn verify_password<D: AuthDatabase + 'static>(
    req: HttpRequest,
    ctx: web::Data<AuthrContext<D>>,
    body: web::Json<VerifyPasswordRequest>,
) -> Result<HttpResponse, ServerError> {
    let authenticated = get_authenticated_session(&req)?;
    let body = body.into_inner();

    verify_password_operation(
        ctx.get_ref(),
        VerifyPasswordInput {
            user_id: authenticated.user.id.to_string(),
            password: body.password,
        },
    )
    .await?;

    tracing::debug!(
        user_id = %authenticated.user.id,
        "Password verified successfully"
    );

    Ok(HttpResponse::Ok().json(json!({
        "status": true
    })))
}

// -------------------- Change Password --------------------

#[tracing::instrument(name = "auth.change_password", skip_all)]
/// Changes the authenticated user's existing password.
pub async fn change_password<D: AuthDatabase + 'static>(
    req: HttpRequest,
    ctx: web::Data<AuthrContext<D>>,
    body: web::Json<ChangePasswordRequest>,
) -> Result<HttpResponse, ServerError> {
    let authenticated = get_authenticated_session(&req)?;
    let body = body.into_inner();

    change_password_operation(
        ctx.get_ref(),
        ChangePasswordInput {
            user_id: authenticated.user.id.to_string(),
            current_password: body.current_password,
            new_password: body.new_password,
            revoke_other_sessions: body.revoke_other_sessions,
            current_session_id: authenticated.session.id.to_string(),
        },
    )
    .await?;

    tracing::info!(
        user_id = %authenticated.user.id,
        revoke_other_sessions = body.revoke_other_sessions,
        "Password changed"
    );

    Ok(HttpResponse::Ok().json(json!({
        "token": null,
        "user": authenticated.user
    })))
}

// -------------------- Set Password --------------------

#[tracing::instrument(name = "auth.set_password", skip_all)]
/// Sets a password for an authenticated user who doesn't already have one.
pub async fn set_password<D: AuthDatabase + 'static>(
    req: HttpRequest,
    ctx: web::Data<AuthrContext<D>>,
    body: web::Json<SetPasswordRequest>,
) -> Result<HttpResponse, ServerError> {
    let authenticated = get_authenticated_session(&req)?;
    let body = body.into_inner();

    set_password_operation(
        ctx.get_ref(),
        SetPasswordInput {
            user_id: authenticated.user.id.to_string(),
            new_password: body.new_password,
        },
    )
    .await?;

    tracing::info!(
        user_id = %authenticated.user.id,
        "Credential password set"
    );

    Ok(HttpResponse::Ok().json(json!({
        "status": true
    })))
}