ch-auth 0.3.2

Authentication and session primitives with explicit security policies
Documentation
//! Typed account authorization for session-backed handlers.

use std::{fmt::Debug, hash::Hash};

use serde::{Serialize, de::DeserializeOwned};

use axum_session::DatabasePool;
use axum_session_auth::Authentication;

use crate::session::AuthSession;

/// Application-owned authorization policy for a loaded account.
pub trait AccountAuthorizer {
    /// Role or permission requirement understood by the application.
    type Role;

    /// Error returned by the application's API boundary.
    type Error;

    /// Creates the error used when no account is present in the session.
    fn unauthenticated_error() -> Self::Error;

    /// Verifies that this account satisfies the requested authorization role.
    fn authorize(&self, required_role: Self::Role) -> Result<(), Self::Error>;
}

/// Session capability used by protected handlers.
pub trait AccountSession {
    /// Account loaded by the session.
    type Account: AccountAuthorizer;

    /// Returns the current account after applying its authorization policy.
    fn authorize(
        &self,
        required_role: <Self::Account as AccountAuthorizer>::Role,
    ) -> Result<&Self::Account, <Self::Account as AccountAuthorizer>::Error>;
}

impl<User, Database, Sessions, Identifier> AccountSession
    for AuthSession<User, Database, Sessions, Identifier>
where
    Database: Clone + Debug + Send + Sync + 'static,
    Sessions: DatabasePool + Clone + Debug + Send + Sync + 'static,
    User: AccountAuthorizer + Authentication<User, Identifier, Database> + Send,
    Identifier: Eq + Default + Clone + Send + Sync + Hash + Serialize + DeserializeOwned + 'static,
{
    type Account = User;

    fn authorize(
        &self,
        required_role: <Self::Account as AccountAuthorizer>::Role,
    ) -> Result<&Self::Account, <Self::Account as AccountAuthorizer>::Error> {
        let account = self
            .current_user
            .as_ref()
            .ok_or_else(User::unauthenticated_error)?;
        account.authorize(required_role)?;
        Ok(account)
    }
}