Skip to main content

fabryk_auth/
lib.rs

1//! Generic authentication primitives for Fabryk.
2//!
3//! Provides:
4//! - [`AuthenticatedUser`] — Identity extracted from a validated token
5//! - [`TokenValidator`] — Trait for async token validation (implement per provider)
6//! - [`AuthLayer`] / [`AuthService`] — Tower middleware parameterised over `TokenValidator`
7//! - [`AuthConfig`] — Configuration for the auth layer
8//! - [`AuthError`] — Auth-specific error types
9
10mod error;
11mod middleware;
12mod user;
13
14pub use error::AuthError;
15pub use middleware::{AuthLayer, AuthService};
16pub use user::{AuthenticatedUser, email_from_parts, user_from_parts};
17
18/// Configuration for the auth middleware.
19#[derive(Clone, Debug, Default)]
20pub struct AuthConfig {
21    /// Whether authentication is enabled. When false, all requests pass through.
22    pub enabled: bool,
23    /// Expected audience (e.g., OAuth client ID).
24    pub audience: String,
25    /// Allowed email domain (e.g., "banyan.com"). Empty string means any domain.
26    pub domain: String,
27}
28
29/// Trait for validating tokens and extracting user identity.
30///
31/// Implement this for each identity provider (Google, Auth0, etc.).
32/// The middleware calls `validate()` with the bearer token and returns
33/// the authenticated user on success.
34pub trait TokenValidator: Send + Sync + 'static {
35    /// Validate a token and return the authenticated user.
36    fn validate(
37        &self,
38        token: &str,
39        config: &AuthConfig,
40    ) -> std::pin::Pin<
41        Box<dyn std::future::Future<Output = Result<AuthenticatedUser, AuthError>> + Send + '_>,
42    >;
43}