authia 0.3.4

High-performance JWT verification library for Ed25519 using WebAssembly
Documentation
use serde::{Deserialize, Serialize};
use std::fmt;

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum ErrorCode {
    TokenExpired,
    InvalidSignature,
    InvalidIssuer,
    InvalidAudience,
    InvalidTokenType,
    MalformedToken,
    InvalidClaims,
    InvalidPublicKey,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AuthiaError {
    pub code: ErrorCode,
    pub message: String,
}

impl AuthiaError {
    pub fn new(code: ErrorCode, message: impl Into<String>) -> Self {
        Self {
            code,
            message: message.into(),
        }
    }

    pub fn token_expired() -> Self {
        Self::new(ErrorCode::TokenExpired, "Token has expired")
    }

    pub fn invalid_signature() -> Self {
        Self::new(ErrorCode::InvalidSignature, "Invalid token signature")
    }

    pub fn invalid_issuer(expected: &str, actual: &str) -> Self {
        Self::new(
            ErrorCode::InvalidIssuer,
            format!("Invalid issuer: expected '{}', got '{}'", expected, actual),
        )
    }

    pub fn invalid_audience(expected: &str, actual: &str) -> Self {
        Self::new(
            ErrorCode::InvalidAudience,
            format!(
                "Invalid audience: expected '{}', got '{}'",
                expected, actual
            ),
        )
    }

    pub fn invalid_token_type(expected: &str, actual: &str) -> Self {
        Self::new(
            ErrorCode::InvalidTokenType,
            format!(
                "Invalid token type: expected '{}', got '{}'",
                expected, actual
            ),
        )
    }

    pub fn malformed_token(reason: impl Into<String>) -> Self {
        Self::new(ErrorCode::MalformedToken, reason)
    }

    pub fn invalid_claims(reason: impl Into<String>) -> Self {
        Self::new(ErrorCode::InvalidClaims, reason)
    }

    pub fn invalid_public_key(reason: impl Into<String>) -> Self {
        Self::new(ErrorCode::InvalidPublicKey, reason)
    }
}

impl fmt::Display for AuthiaError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{:?}: {}", self.code, self.message)
    }
}

impl std::error::Error for AuthiaError {}