use std::fmt; use crate::pow::PowError; #[derive(Debug)] pub enum AuthError { BadRequest(String), InvalidCredentials, Unauthorized, Forbidden, NotFound, Conflict(String), RateLimited, PowFailed, Internal(String), } impl fmt::Display for AuthError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::BadRequest(message) => write!(f, "{message}"), Self::InvalidCredentials => write!(f, "invalid credentials"), Self::Unauthorized => write!(f, "unauthorized"), Self::Forbidden => write!(f, "forbidden"), Self::NotFound => write!(f, "not found"), Self::Conflict(message) => write!(f, "{message}"), Self::RateLimited => write!(f, "rate limit exceeded"), Self::PowFailed => write!(f, "proof of work failed"), Self::Internal(message) => write!(f, "{message}"), } } } impl std::error::Error for AuthError {} export::db_error_conversions!(AuthError); export::redis_error_conversion!(AuthError); export::export_error_conversion!(AuthError); export::json_payload_conversion!(AuthError); impl From for AuthError { fn from(error: PowError) -> Self { match error { PowError::NotConfigured | PowError::InvalidKey => { Self::Internal("pow service is not configured".to_string()) } PowError::Missing => Self::BadRequest("pow challenge missing".to_string()), PowError::Expired => Self::BadRequest("pow challenge expired".to_string()), PowError::Malformed | PowError::InvalidSolution => { Self::BadRequest("invalid pow solution".to_string()) } PowError::InvalidSignature => Self::BadRequest("invalid pow challenge".to_string()), } } } export::api_error! { log: "auth", pub enum ApiError { BadRequest(400, "request failed validation"), InvalidCredentials(400, "credentials rejected"), Unauthorized(401, "authentication required"), Forbidden(403, "operation not allowed"), NotFound(404, "resource not found"), Conflict(409, "resource conflict"), RateLimited(429, "rate limit exceeded"), Internal(500, "internal server error"), } } impl From for ApiError { fn from(error: AuthError) -> Self { match error { AuthError::BadRequest(msg) => Self::bad_request(msg), AuthError::InvalidCredentials => { Self::InvalidCredentials(Self::payload(400, "invalid credentials")) } AuthError::Unauthorized => Self::unauthorized(), AuthError::Forbidden => Self::forbidden(), AuthError::NotFound => Self::not_found("auth resource not found"), AuthError::Conflict(msg) => Self::conflict(msg), AuthError::RateLimited => Self::rate_limited_exceeded(), AuthError::PowFailed => Self::build( 400, Self::payload(400, "proof of work failed").with_error_code("pow_failed"), ), AuthError::Internal(message) => Self::internal(message), } } }