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;
#[derive(Debug, Error)]
pub enum ServerError {
#[error("Invalid authentication configuration: {0}")]
InvalidConfiguration(&'static str),
#[error("Invalid email")]
InvalidEmail,
#[error("Invalid name")]
InvalidName,
#[error("Invalid password")]
InvalidPassword,
#[error("Invalid password reset token")]
InvalidResetToken,
#[error("Invalid callback URL")]
InvalidCallbackUrl,
#[error("Authentication is disabled")]
AuthenticationDisabled,
#[error("Invalid credentials")]
InvalidCredentials,
#[error("Email address has not been verified")]
EmailNotVerified,
#[error("User already exists")]
UserAlreadyExists,
#[error("User not found")]
UserNotFound,
#[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,
#[error("Session is not fresh")]
SessionNotFresh,
#[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,
#[error("Password hashing failed")]
PasswordHashingFailed,
#[error("Password verification failed")]
PasswordVerificationFailed,
#[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),
#[error("Database operation failed")]
Database(#[source] AuthDatabaseError),
#[error("Internal server error")]
Internal,
#[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,
}
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 {
AuthrCoreError::InvalidConfiguration(m) => Self::InvalidConfiguration(m),
AuthrCoreError::EmailVerificationDisabled => Self::EmailVerificationDisabled,
AuthrCoreError::InvalidVerificationToken => Self::InvalidVerificationToken,
AuthrCoreError::VerificationExpired => Self::VerificationExpired,
AuthrCoreError::EmailVerificationSenderMissing => Self::Internal,
AuthrCoreError::VerificationEmailDeliveryFailed => Self::Internal,
AuthrCoreError::InvalidEmail => Self::InvalidEmail,
AuthrCoreError::InvalidName => Self::InvalidName,
AuthrCoreError::InvalidPassword => Self::InvalidPassword,
AuthrCoreError::PasswordRequired => Self::InvalidPassword,
AuthrCoreError::InvalidCredentials => Self::InvalidCredentials,
AuthrCoreError::AuthenticationDisabled(_) => Self::AuthenticationDisabled,
AuthrCoreError::EmailNotVerified => Self::EmailNotVerified,
AuthrCoreError::InvalidCallbackUrl => Self::InvalidCallbackUrl,
AuthrCoreError::UserNotFound => Self::UserNotFound,
AuthrCoreError::UserAlreadyExists => Self::UserAlreadyExists,
AuthrCoreError::NoFieldsToUpdate => Self::Internal,
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,
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)
}
AuthrCoreError::SessionNotFresh => Self::SessionNotFresh,
AuthrCoreError::ProviderNotFound(_) => Self::ProviderNotFound,
AuthrCoreError::ProviderInitialization => Self::ProviderInitialization,
AuthrCoreError::ProviderClientMissing => Self::ProviderClientMissing,
AuthrCoreError::OAuthOperationFailed(_) => Self::OAuthAuthorizationFailed,
AuthrCoreError::Database(error) => Self::Database(error),
AuthrCoreError::Store(AuthrStoreError::Database(error)) => Self::Database(error),
AuthrCoreError::Store(AuthrStoreError::Crypto(_)) => Self::Internal,
}
}
}
impl ResponseError for ServerError {
fn status_code(&self) -> StatusCode {
match self {
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,
Self::InvalidCredentials
| Self::EmailNotVerified
| Self::SessionNotFresh
| Self::AccountLinkSessionInvalid => StatusCode::UNAUTHORIZED,
Self::AuthenticationDisabled
| Self::PasswordResetDisabled
| Self::AccountLinkingDisabled
| Self::CannotUnlinkLastAccount
| Self::EmailVerificationDisabled => StatusCode::FORBIDDEN,
Self::UserNotFound | Self::AccountNotFound | Self::ProviderNotFound => {
StatusCode::NOT_FOUND
}
Self::UserAlreadyExists | Self::AccountAlreadyLinked => StatusCode::CONFLICT,
Self::AccountLinkTransactionExpired | Self::VerificationExpired => StatusCode::GONE,
_ => StatusCode::INTERNAL_SERVER_ERROR,
}
}
fn error_response(&self) -> HttpResponse {
HttpResponse::build(self.status_code()).json(serde_json::json!({
"error": self.to_string()
}))
}
}