token_source/
lib.rs

1//! # token-source
2//!
3//! A lightweight library to provide common traits and structs for token sources.
4//!
5//! ## Token source
6//!
7//! A token source is anything capable of sourcing any type of token.
8//! Tokens are originally meant for authentication (OAuth2, Id, Noop, etc.), but can be used for any purpose.
9//!
10//! ## Token source provider
11//!
12//! A token source provider own the token source and provides access to it.
13
14#![warn(missing_docs)]
15
16use std::fmt::Debug;
17use std::sync::Arc;
18
19#[cfg(feature = "async-token-source")]
20use async_trait::async_trait;
21
22/// A TokenSource abstracts how a token is obtained or generated.
23///
24/// This is where you would implement the logic to fetch a token from a local cache,
25/// or a remote server (for example requesting a new token from an OAuth2 server).
26#[cfg(feature = "async-token-source")]
27#[async_trait]
28pub trait TokenSource: Send + Sync + Debug {
29    /// Returns a valid token
30    async fn token(&self) -> Result<String, Box<dyn std::error::Error + Send + Sync>>;
31}
32#[cfg(not(feature = "async-token-source"))]
33pub trait TokenSource: Send + Sync + Debug {
34    /// Returns a valid token
35    fn token(&self) -> Result<String, Box<dyn std::error::Error + Send + Sync>>;
36}
37
38/// A TokenSourceProvider provides a TokenSource implementation.
39pub trait TokenSourceProvider: Send + Sync + Debug {
40    /// Returns the token source implementation
41    fn token_source(&self) -> Arc<dyn TokenSource>;
42}
43
44/// A Noop token source provider.
45///
46/// You can use this as fallback or dummy token source provider.
47#[derive(Debug)]
48pub struct NoopTokenSourceProvider {}
49
50impl TokenSourceProvider for NoopTokenSourceProvider {
51    fn token_source(&self) -> Arc<dyn TokenSource> {
52        panic!("This is dummy token source provider. Please use any crate providing a real implementation.")
53    }
54}