Skip to main content

trojan_auth/
traits.rs

1//! Authentication backend trait.
2
3use std::sync::Arc;
4
5use async_trait::async_trait;
6
7use crate::error::AuthError;
8use crate::result::AuthResult;
9
10/// Trait for authentication backends.
11///
12/// Implementations must be thread-safe (`Send + Sync`) as they may be
13/// called concurrently from multiple connections.
14#[async_trait]
15pub trait AuthBackend: Send + Sync {
16    /// Verify a password hash.
17    ///
18    /// # Arguments
19    /// * `hash` - The SHA224 hex-encoded hash of the password
20    ///
21    /// # Returns
22    /// * `Ok(AuthResult)` - Authentication successful
23    /// * `Err(AuthError)` - Authentication failed
24    async fn verify(&self, hash: &str) -> Result<AuthResult, AuthError>;
25
26    /// Optional: Record traffic usage for a user.
27    ///
28    /// Default implementation does nothing.
29    #[inline]
30    async fn record_traffic(&self, _user_id: &str, _bytes: u64) -> Result<(), AuthError> {
31        Ok(())
32    }
33}
34
35/// Blanket implementation for `Arc<A>` where `A: AuthBackend`.
36///
37/// This allows passing `Arc<AuthBackend>` directly to functions expecting `impl AuthBackend`.
38#[async_trait]
39impl<A: AuthBackend + ?Sized> AuthBackend for Arc<A> {
40    #[inline]
41    async fn verify(&self, hash: &str) -> Result<AuthResult, AuthError> {
42        (**self).verify(hash).await
43    }
44
45    #[inline]
46    async fn record_traffic(&self, user_id: &str, bytes: u64) -> Result<(), AuthError> {
47        (**self).record_traffic(user_id, bytes).await
48    }
49}
50
51/// Blanket implementation for `Box<A>` where `A: AuthBackend`.
52#[async_trait]
53impl<A: AuthBackend + ?Sized> AuthBackend for Box<A> {
54    #[inline]
55    async fn verify(&self, hash: &str) -> Result<AuthResult, AuthError> {
56        (**self).verify(hash).await
57    }
58
59    #[inline]
60    async fn record_traffic(&self, user_id: &str, bytes: u64) -> Result<(), AuthError> {
61        (**self).record_traffic(user_id, bytes).await
62    }
63}