authr_http 0.1.0

Actix Web integration for authr.
Documentation
use std::error::Error;

use actix_web::{HttpResponse, ResponseError, http::StatusCode};
use thiserror::Error;

use authr_core::{database::AuthDatabaseError, error::AuthrCoreError, store::AuthrStoreError};
use authr_oauth::OAuthError;

/// Errors encountered while handling HTTP authentication requests.
#[derive(Debug, Error)]
pub enum ServerError {
    // ----- Configuration
    #[error("Invalid authentication configuration: {0}")]
    InvalidConfiguration(&'static str),

    // ----- Validation
    #[error("Invalid email")]
    InvalidEmail,
    #[error("Invalid name")]
    InvalidName,
    #[error("Invalid password")]
    InvalidPassword,
    #[error("Invalid password reset token")]
    InvalidResetToken,
    #[error("Invalid callback URL")]
    InvalidCallbackUrl,

    // ----- Authentication
    #[error("Authentication is disabled")]
    AuthenticationDisabled,
    #[error("Invalid credentials")]
    InvalidCredentials,
    #[error("Email address has not been verified")]
    EmailNotVerified,

    // ----- Users
    #[error("User already exists")]
    UserAlreadyExists,
    #[error("User not found")]
    UserNotFound,

    // ----- Accounts
    #[error("Account linking is disabled")]
    AccountLinkingDisabled,
    #[error("Account not found")]
    AccountNotFound,
    #[error("Account is already linked to another user")]
    AccountAlreadyLinked,
    #[error("Cannot unlink the last authentication account")]
    CannotUnlinkLastAccount,
    #[error("Provider account email does not match the user's email")]
    AccountEmailMismatch,
    #[error("Account linking transaction is invalid")]
    InvalidAccountLinkTransaction,
    #[error("Account linking transaction has expired")]
    AccountLinkTransactionExpired,
    #[error("The original session is no longer valid")]
    AccountLinkSessionInvalid,
    #[error("Provider returned an invalid identity")]
    InvalidProviderIdentity,
    #[error("Account has no refresh token")]
    RefreshTokenMissing,

    // ----- Sessions
    #[error("Session is not fresh")]
    SessionNotFresh,

    // ----- Password Reset
    #[error("Password reset is not enabled")]
    PasswordResetDisabled,
    #[error("Failed to deliver password reset email")]
    PasswordResetDeliveryFailed(#[source] Box<dyn Error + Send + Sync>),
    #[error("Password is already set")]
    PasswordAlreadySet,

    // ----- Cryptography
    #[error("Password hashing failed")]
    PasswordHashingFailed,
    #[error("Password verification failed")]
    PasswordVerificationFailed,

    // ----- OAuth
    #[error("OAuth provider not found")]
    ProviderNotFound,
    #[error("OAuth provider initialization failed")]
    ProviderInitialization,
    #[error("OAuth client not found")]
    ProviderClientMissing,
    #[error("OAuth authorization failed")]
    OAuthAuthorizationFailed,
    #[error("OAuth token exchange failed")]
    OAuthTokenExchangeFailed,
    #[error("OAuth user information retrieval failed")]
    OAuthUserInfoFailed,
    #[error("OAuth operation failed")]
    OAuth(#[source] OAuthError),

    // ----- Database
    #[error("Database operation failed")]
    Database(#[source] AuthDatabaseError),

    // ----- General
    #[error("Internal server error")]
    Internal,

    // ----- Email Verification
    #[error("Email verification is disabled")]
    EmailVerificationDisabled,

    #[error("Invalid email verification token")]
    InvalidVerificationToken,

    #[error("Email verification token has expired")]
    VerificationExpired,

    #[error("Email address does not match the authenticated user")]
    EmailMismatch,

    #[error("Email address is already verified")]
    EmailAlreadyVerified,
}

// -------------------- Conversions --------------------

impl From<AuthDatabaseError> for ServerError {
    fn from(error: AuthDatabaseError) -> Self {
        Self::Database(error)
    }
}

impl From<OAuthError> for ServerError {
    fn from(error: OAuthError) -> Self {
        Self::OAuth(error)
    }
}

impl From<AuthrStoreError> for ServerError {
    fn from(error: AuthrStoreError) -> Self {
        match error {
            AuthrStoreError::Database(error) => Self::Database(error),
            AuthrStoreError::Crypto(_) => Self::Internal,
        }
    }
}

impl From<AuthrCoreError> for ServerError {
    fn from(error: AuthrCoreError) -> Self {
        match error {
            // Configuration
            AuthrCoreError::InvalidConfiguration(m) => Self::InvalidConfiguration(m),

            // Email verification
            AuthrCoreError::EmailVerificationDisabled => Self::EmailVerificationDisabled,
            AuthrCoreError::InvalidVerificationToken => Self::InvalidVerificationToken,
            AuthrCoreError::VerificationExpired => Self::VerificationExpired,
            AuthrCoreError::EmailVerificationSenderMissing => Self::Internal,
            AuthrCoreError::VerificationEmailDeliveryFailed => Self::Internal,

            // Validation
            AuthrCoreError::InvalidEmail => Self::InvalidEmail,
            AuthrCoreError::InvalidName => Self::InvalidName,
            AuthrCoreError::InvalidPassword => Self::InvalidPassword,
            AuthrCoreError::PasswordRequired => Self::InvalidPassword,

            // Authentication
            AuthrCoreError::InvalidCredentials => Self::InvalidCredentials,
            AuthrCoreError::AuthenticationDisabled(_) => Self::AuthenticationDisabled,
            AuthrCoreError::EmailNotVerified => Self::EmailNotVerified,
            AuthrCoreError::InvalidCallbackUrl => Self::InvalidCallbackUrl,

            // Users
            AuthrCoreError::UserNotFound => Self::UserNotFound,
            AuthrCoreError::UserAlreadyExists => Self::UserAlreadyExists,
            AuthrCoreError::NoFieldsToUpdate => Self::Internal,

            // Accounts
            AuthrCoreError::AccountLinkingDisabled => Self::AccountLinkingDisabled,
            AuthrCoreError::AccountNotFound => Self::AccountNotFound,
            AuthrCoreError::AccountAlreadyLinked => Self::AccountAlreadyLinked,
            AuthrCoreError::CannotUnlinkLastAccount => Self::CannotUnlinkLastAccount,
            AuthrCoreError::AccountEmailMismatch => Self::AccountEmailMismatch,
            AuthrCoreError::InvalidAccountLinkTransaction => Self::InvalidAccountLinkTransaction,
            AuthrCoreError::AccountLinkTransactionExpired => Self::AccountLinkTransactionExpired,
            AuthrCoreError::AccountLinkSessionInvalid => Self::AccountLinkSessionInvalid,
            AuthrCoreError::InvalidProviderIdentity => Self::InvalidProviderIdentity,
            AuthrCoreError::RefreshTokenMissing => Self::RefreshTokenMissing,
            AuthrCoreError::TokenRefreshUnsupported => Self::Internal,

            // Passwords
            AuthrCoreError::PasswordHashingFailed => Self::PasswordHashingFailed,
            AuthrCoreError::PasswordVerificationFailed => Self::PasswordVerificationFailed,
            AuthrCoreError::CredentialAccountNotFound => Self::InvalidCredentials,
            AuthrCoreError::PasswordAlreadySet => Self::PasswordAlreadySet,
            AuthrCoreError::PasswordResetDisabled => Self::PasswordResetDisabled,
            AuthrCoreError::PasswordResetDeliveryFailed(error) => {
                Self::PasswordResetDeliveryFailed(error)
            }

            // Sessions
            AuthrCoreError::SessionNotFresh => Self::SessionNotFresh,

            // OAuth
            AuthrCoreError::ProviderNotFound(_) => Self::ProviderNotFound,
            AuthrCoreError::ProviderInitialization => Self::ProviderInitialization,
            AuthrCoreError::ProviderClientMissing => Self::ProviderClientMissing,
            AuthrCoreError::OAuthOperationFailed(_) => Self::OAuthAuthorizationFailed,

            // Database
            AuthrCoreError::Database(error) => Self::Database(error),

            // Store
            AuthrCoreError::Store(AuthrStoreError::Database(error)) => Self::Database(error),
            AuthrCoreError::Store(AuthrStoreError::Crypto(_)) => Self::Internal,
        }
    }
}

// -------------------- Actix Integration --------------------

impl ResponseError for ServerError {
    fn status_code(&self) -> StatusCode {
        match self {
            // 400 Bad Request
            Self::InvalidEmail
            | Self::InvalidName
            | Self::InvalidPassword
            | Self::InvalidResetToken
            | Self::InvalidCallbackUrl
            | Self::PasswordAlreadySet
            | Self::InvalidAccountLinkTransaction
            | Self::AccountEmailMismatch
            | Self::InvalidVerificationToken
            | Self::EmailMismatch
            | Self::EmailAlreadyVerified => StatusCode::BAD_REQUEST,

            // 401 Unauthorized
            Self::InvalidCredentials
            | Self::EmailNotVerified
            | Self::SessionNotFresh
            | Self::AccountLinkSessionInvalid => StatusCode::UNAUTHORIZED,

            // 403 Forbidden
            Self::AuthenticationDisabled
            | Self::PasswordResetDisabled
            | Self::AccountLinkingDisabled
            | Self::CannotUnlinkLastAccount
            | Self::EmailVerificationDisabled => StatusCode::FORBIDDEN,

            // 404 Not Found
            Self::UserNotFound | Self::AccountNotFound | Self::ProviderNotFound => {
                StatusCode::NOT_FOUND
            }

            // 409 Conflict
            Self::UserAlreadyExists | Self::AccountAlreadyLinked => StatusCode::CONFLICT,

            // 410 Gone
            Self::AccountLinkTransactionExpired | Self::VerificationExpired => StatusCode::GONE,

            // 500 Internal Server Error
            _ => StatusCode::INTERNAL_SERVER_ERROR,
        }
    }

    fn error_response(&self) -> HttpResponse {
        HttpResponse::build(self.status_code()).json(serde_json::json!({
            "error": self.to_string()
        }))
    }
}