capy-auth 0.10.0

Optional database-backed browser sessions and explicit authorization for Capy.
Documentation
//! Framework-owned verification proofs with an application-owned delivery adapter.
use crate::{LocalResetDelivery, MemoryResetDelivery, ResetDelivery, ResetMessage, Secret};
use capy_core::Result;
use std::{future::Future, pin::Pin};

/// Deliver email-verification credentials privately; never log or queue plaintext proofs.
pub trait VerificationDelivery: Send + Sync + 'static {
    /// Accept a proof for delivery. Prefer a frontend URL fragment, never a query string.
    fn deliver(
        &self,
        message: VerificationMessage,
    ) -> Pin<Box<dyn Future<Output = Result<()>> + Send + '_>>;
    /// Declare an adapter that must be refused in production.
    fn development_only(&self) -> bool {
        false
    }
}
/// Single-use proof. It is bound to a user and their current address in the database.
pub struct VerificationMessage {
    /// Private recipient address.
    pub email: String,
    /// Verification credential, distinct from password-reset credentials.
    pub token: Secret,
    /// Absolute expiration in Unix seconds.
    pub expires_at: i64,
}
impl std::fmt::Debug for VerificationMessage {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("VerificationMessage([REDACTED])")
    }
}
impl From<VerificationMessage> for ResetMessage {
    fn from(message: VerificationMessage) -> Self {
        Self {
            email: message.email,
            token: message.token,
            expires_at: message.expires_at,
        }
    }
}
/// Private local file delivery, sharing the reset inbox's permissions and symlink checks.
/// Select a separate directory, such as `.capy-verification-outbox`, outside public assets.
#[derive(Clone, Debug)]
pub struct LocalVerificationDelivery(LocalResetDelivery);
impl LocalVerificationDelivery {
    /// Select the private development-only directory.
    pub fn new(directory: impl Into<std::path::PathBuf>) -> Self {
        Self(LocalResetDelivery::new(directory))
    }
}
impl VerificationDelivery for LocalVerificationDelivery {
    fn deliver(
        &self,
        message: VerificationMessage,
    ) -> Pin<Box<dyn Future<Output = Result<()>> + Send + '_>> {
        self.0.deliver(message.into())
    }
    fn development_only(&self) -> bool {
        true
    }
}
/// Bounded, redacted verification inbox for integration tests. Refused in production.
#[derive(Clone, Default, Debug)]
pub struct MemoryVerificationDelivery(MemoryResetDelivery);
impl MemoryVerificationDelivery {
    /// Drain private delivery messages; the caller must not log the returned credentials.
    pub fn take(&self) -> Vec<VerificationMessage> {
        self.0
            .take()
            .into_iter()
            .map(|message| VerificationMessage {
                email: message.email,
                token: message.token,
                expires_at: message.expires_at,
            })
            .collect()
    }
}
impl VerificationDelivery for MemoryVerificationDelivery {
    fn deliver(
        &self,
        message: VerificationMessage,
    ) -> Pin<Box<dyn Future<Output = Result<()>> + Send + '_>> {
        self.0.deliver(message.into())
    }
    fn development_only(&self) -> bool {
        true
    }
}

/// Verification input. Send over a CSRF-protected request body, never a URL query.
#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct VerifyEmailRequest {
    /// Single-use proof obtained through the private delivery adapter.
    #[schemars(with = "String")]
    pub token: Secret,
}
/// Verification state for the current authenticated identity.
#[derive(Debug, serde::Serialize, schemars::JsonSchema)]
pub struct VerificationStatus {
    /// Whether the current address has been verified.
    pub verified: bool,
}

/// Remove expired optional verification proofs. Call only after applying its migration.
pub async fn prune(db: &sea_orm::DatabaseConnection) -> Result<u64> {
    use sea_orm::{ColumnTrait, EntityTrait, QueryFilter};
    Ok(crate::models::verification::Entity::delete_many()
        .filter(crate::models::verification::Column::ExpiresAt.lte(crate::runtime::now()))
        .exec(db)
        .await?
        .rows_affected)
}

/// Additional reversible migration; existing identity migrations must not be edited.
pub mod migration {
    use sea_orm_migration::prelude::*;
    /// Register after the identity migration before enabling email-verification routes.
    #[derive(DeriveMigrationName)]
    pub struct EmailVerificationMigration;
    #[async_trait::async_trait]
    impl MigrationTrait for EmailVerificationMigration {
        async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
            manager
                .create_table(
                    Table::create()
                        .table(Alias::new("email_verification_tokens"))
                        .col(
                            ColumnDef::new(Alias::new("user_id"))
                                .big_integer()
                                .not_null()
                                .primary_key(),
                        )
                        .col(
                            ColumnDef::new(Alias::new("token_hash"))
                                .string_len(64)
                                .not_null(),
                        )
                        .col(
                            ColumnDef::new(Alias::new("email"))
                                .string_len(254)
                                .not_null(),
                        )
                        .col(
                            ColumnDef::new(Alias::new("expires_at"))
                                .big_integer()
                                .not_null(),
                        )
                        .foreign_key(
                            ForeignKey::create()
                                .from_col(Alias::new("user_id"))
                                .to(Alias::new("users"), Alias::new("id"))
                                .on_delete(ForeignKeyAction::Cascade),
                        )
                        .to_owned(),
                )
                .await
        }
        async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
            manager
                .drop_table(
                    Table::drop()
                        .table(Alias::new("email_verification_tokens"))
                        .to_owned(),
                )
                .await
        }
    }
}